Emmanuel Akinfulubi

JavaScriptRecursion

Sum an array using recursion in JavaScript

Beginner · 4 min read

Adding up a list of numbers is something every program does: a shopping cart total, the points in a quiz, the steps walked this week. In real code you would use a loop or reduce. Writing it with recursion is still worth doing once, because it teaches the most important rule of recursion: where the base case belongs.

In this tutorial you will write a recursive sum of an array, then a second version that does the same job without copying the array at every step. You need to know what an array and a function are. Recursion and destructuring are explained below.

The idea

A recursive function handles one small piece and calls itself for the rest. For a sum, the small piece is the first number:

Worked example

sum([1, 2, 3]) = 1 + sum([2, 3])
               = 1 + (2 + sum([3]))
               = 1 + (2 + (3 + sum([])))

Each call works on a shorter array. Eventually the array is empty, and the sum of no numbers is 0. That is the base case, the point where the function answers without calling itself.

Taking an array apart

Destructuring pulls items out of an array into variables. With ...rest, everything after the first item lands in a new array:

JavaScript

const [first, ...rest] = [1, 2, 3];
console.log(first); // 1
console.log(rest);  // [ 2, 3 ]

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

4 Sum of an array

easy

Add up an array of numbers recursively. Then look at what the tidy one-liner costs.

Stuck? Three hints, smallest first
  1. 1. The base case is the empty array returning 0, which makes every other case work.
  2. 2. [first, ...rest] is elegant but copies the array at every level.
  3. 3. Passing an index instead of a smaller array does no copying at all.

Step 1: the version everyone writes first

Put the base case at the top, then split off the first number and add it to the sum of the rest:

Step 1

function sumCopying(values) {
  if (values.length === 0) return 0;
  const [first, ...rest] = values;
  return first + sumCopying(rest);
}
console.log(sumCopying([1, 2, 3, 4, 5, 6])); // 21
console.log(sumCopying([]));                 // 0
console.log(sumCopying([5, -3, 1]));         // 3

The empty array returns 0, and negative numbers simply subtract.

Step 2: the wrong base case

It is tempting to stop at one item instead, since "the sum of one number is that number". Try it on an empty array:

JavaScript

function sumBad(values) {
  if (values.length === 1) return values[0];
  const [first, ...rest] = values;
  return first + sumBad(rest);
}
console.log(sumBad([1, 2, 3])); // 6
try {
  sumBad([]);
} catch (e) {
  console.log(e.constructor.name); // 'RangeError'
}

An empty array never has length 1, and rest of an empty array is another empty array. So the function calls itself with [] forever, until JavaScript throws RangeError: Maximum call stack size exceeded. Putting the base case on the empty array makes every input work, including the empty one.

Step 3: count the copies

...rest makes a brand-new array on every call. For six numbers that is six new arrays, each one a little shorter than the last:

Step 3

let copies = 0;
function sumCounted(values) {
  if (values.length === 0) return 0;
  const [first, ...rest] = values;
  copies++;
  return first + sumCounted(rest);
}
sumCounted([1, 2, 3, 4, 5, 6]);
console.log(copies); // 6

For a short list that's nothing. For a list of 10,000 numbers, the copies add up to about 50 million items, all thrown away straight after.

Step 4: walk an index instead

Instead of making the array smaller, keep the same array and pass along a position i. A default parameter (i = 0) means the caller doesn't have to supply it:

Step 4

function sumIndexed(values, i = 0) {
  if (i >= values.length) return 0;
  return values[i] + sumIndexed(values, i + 1);
}
console.log(sumIndexed([1, 2, 3, 4, 5, 6])); // 21

The base case is now "the position has gone past the end", which is the same idea as "nothing left". No array is copied at all.

Step 5: what you would actually ship

reduce walks the array and keeps a running total. The 0 at the end is the starting total, which also makes an empty array return 0:

Step 5

const nums = [1, 2, 3, 4, 5, 6];
console.log(nums.reduce((a, b) => a + b, 0)); // 21
console.log(nums);                            // [ 1, 2, 3, 4, 5, 6 ]

None of these versions change the original array.

Step 6: a warning about decimals

JavaScript

console.log(0.1 + 0.2 === 0.3); // false
console.log(0.1 + 0.2);         // 0.30000000000000004

This isn't a bug in your sum. Computers store decimals in binary, and many decimals, like 0.1, can't be stored exactly. For money, add whole kobo or cents and divide at the end.

The full solution

The panel has the copying version, the index version and reduce, plus a counter that proves how many arrays the copying version makes. Press Run to see the output.

The answer

// The version everyone writes first. Readable, and quietly O(n^2) on memory:
// each call allocates a fresh `rest` array.
function sumCopying(values) {
  if (values.length === 0) return 0;          // empty is the real base case
  const [first, ...rest] = values;
  return first + sumCopying(rest);
}

// Same recursion, no copying: walk an index instead of shrinking the array.
function sumIndexed(values, i = 0) {
  if (i >= values.length) return 0;
  return values[i] + sumIndexed(values, i + 1);
}

// Count the arrays each version allocates, to make the difference visible.
let copies = 0;
function sumCounted(values) {
  if (values.length === 0) return 0;
  const [first, ...rest] = values;
  copies++;
  return first + sumCounted(rest);
}
sumCounted([1, 2, 3, 4, 5, 6]);

const nums = [1, 2, 3, 4, 5, 6];

console.log('sumCopying :', sumCopying(nums));
console.log('sumIndexed :', sumIndexed(nums));
console.log('reduce     :', nums.reduce((a, b) => a + b, 0));
console.log('arrays allocated for 6 items:', copies);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test("the example sums to 21", sumCopying(nums), 21);
test('the indexed version agrees', sumIndexed(nums), 21);
test('reduce agrees', nums.reduce((a, b) => a + b, 0), 21);
test('an empty array sums to 0', sumCopying([]), 0);
test('one element', sumCopying([7]), 7);
test('negatives subtract', sumCopying([5, -3, 1]), 3);
test('the copying version allocates one array per element', copies, 6);
test('the input is not modified', nums, [1, 2, 3, 4, 5, 6]);
test('decimals warn you about floating point', sumCopying([0.1, 0.2]) === 0.3, false);

reduce((a, b) => a + b, 0) is the answer you would ship. The recursion is worth writing once because it shows where the base case belongs: on the empty array, not on the one-element array. Get that right and the empty input works for free. The last assertion is a reminder that carries across the whole course — 0.1 + 0.2 is not 0.3 in any language using binary floating point, so money belongs in kobo, not naira.

Common mistakes

  • Making one item the base case. An empty array then recurses forever. Stop at the empty array and return 0.
  • Forgetting the 0 in reduce. [].reduce((a, b) => a + b) throws a TypeError because there is nothing to start from.
  • Comparing decimal totals with ===. 0.1 + 0.2 is not exactly 0.3. Work in whole units, or compare with a small tolerance.

Try it yourself

  1. Write productOf(values) that multiplies the numbers recursively. What must the empty array return now?
  2. Write maxOf(values) that finds the largest number recursively, using the index approach.
  3. Change sumIndexed to sum nested arrays too, so [1, [2, 3], [4]] gives 10. (Hint: Array.isArray.)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.