Recursion Basics - Adding Numbers in an Array with Javascript
comments

Last updated 31 October 2014

Recursion can be confusing, especially for people new to programming. I thought I'd post a very simple example here to help beginners.

The problem

Let's say you want to add all the numbers in an array without using a loop. (Why can't you use a loop? Because.) If you knew beforehand the number of items in the array you could write:

function addArray(arrayOfNums) {
    return arrayOfNums[0] + arrayOfNums[1];
}

That would work great for arrays with only 2 numbers. You could write out as many arrayOfNums[x] + as you wanted, but what if you needed to add an array with hundreds of numbers? Enter recursion. Try this:

function addArray(arrayOfNums) {
    return arrayOfNums.shift() + addArray(arrayOfNums);
}

What is happening there? arrayOfNums.shift() removes the first item in an array and returns that item, so you are basically asking your code to add the first number in the array to the sum (using the addArray function) of the remaining items in the array. The function keeps calling itself using progressively smaller arrays until it has added all the numbers together. That is the magic of recursion.

So we're all set? Unfortunately, no. Give it a try and you'll get an infinite loop! You need to set a condition upon which the recursion will end and the function will exit.

In this case, it makes sense to just return 0 if the array is empty because the sum of an empty array should be 0.

function addArray(arrayOfNums) {
    if (arrayOfNums.length === 0) { return 0; }
    return arrayOfNums.shift() + addArray(arrayOfNums);
}

Now if you run this code you will get the expected results! I hope this can help a beginner get the hang of recursion.

comments powered by Disqus