← JavaScript

Intermediate · 17 of 17 · 15 min read

Recursive sum and range

Two exercises that come up constantly, written four ways each, with the accumulator pattern that generalises to the rest.

  • Recursion

These two exercises are small enough to write under pressure and rich enough to show whether you understand the call stack. They also introduce the accumulator pattern, which is how almost every non-trivial recursion is written.

Recursive sum

Sum every integer from 1 to n:

function sum(n) {
  if (n <= 0) return 0;   // base case
  return n + sum(n - 1);  // add on the way back up
}

console.log(sum(5));  // 15
console.log(sum(1));  // 1
console.log(sum(0));  // 0  — the base case guards this
console.log(sum(-3)); // 0  — and this, because the test is <= not ===

The trace, which is the thing to be able to draw:

sum(3) → 3 + sum(2)
         sum(2) → 2 + sum(1)
                  sum(1) → 1 + sum(0)
                           sum(0) → 0      ← base case
                  sum(1) → 1 + 0 = 1
         sum(2) → 2 + 1 = 3
sum(3) → 3 + 3 = 6

Summing an array

The same shape, with the array shrinking instead of the number:

function sumArray(arr) {
  if (arr.length === 0) return 0;
  const [first, ...rest] = arr;    // destructure off the head
  return first + sumArray(rest);
}

console.log(sumArray([1, 2, 3, 4])); // 10
console.log(sumArray([]));           // 0

Clean, and quietly expensive: ...rest copies the remaining elements on every call, so this is O(n²) in memory traffic. An index avoids the copies:

function sumArrayFast(arr, i = 0) {
  if (i >= arr.length) return 0;
  return arr[i] + sumArrayFast(arr, i + 1); // one array, a moving index
}

console.log(sumArrayFast([1, 2, 3, 4])); // 10

With an accumulator

Carry the running total down instead of adding on the way back. This is the tail-recursive form, and the pattern that generalises:

function sumAcc(n, total = 0) {
  if (n <= 0) return total;
  return sumAcc(n - 1, total + n); // nothing left to do with the result
}

console.log(sumAcc(5)); // 15
Adds on the way back Accumulator
Shape return n + f(n - 1) return f(n - 1, total + n)
Pending work per frame an addition none
Reads like the mathematical definition a loop
Raises the depth limit in JS no no — see below

The last row surprises people. The accumulator version is a tail call, and the spec defines tail-call optimisation — but V8 and most other engines never implemented it, so both versions keep n frames and both overflow at the same depth:

// sumAcc(100000); // RangeError: Maximum call stack size exceeded

So the accumulator is about clarity and about the shape of the code, not about depth. When the depth grows with the size of the input, use a loop:

function sumLoop(n) {
  let total = 0;
  for (let i = 1; i <= n; i++) total += i;
  return total;
}
console.log(sumLoop(100_000)); // 5000050000

// Or, for this particular problem, no iteration at all:
const sumFormula = (n) => (n * (n + 1)) / 2;
console.log(sumFormula(100_000)); // 5000050000 — O(1)

Knowing that last one is worth a line in an interview: the recursion demonstrates the technique, the formula is the right answer in production.

Recursive range

Build [start, …, end]:

function range(start, end) {
  if (start > end) return [];                 // base case
  return [start, ...range(start + 1, end)];   // prepend, then the smaller range
}

console.log(range(1, 4));  // [1, 2, 3, 4]
console.log(range(3, 3));  // [3]
console.log(range(5, 1));  // []  — base case hit immediately

Where the pieces go decides the order, and this is the detail the trace question tests:

function descending(start, end) {
  if (start > end) return [];
  return [...descending(start + 1, end), start]; // start goes last
}

console.log(descending(1, 4)); // [4, 3, 2, 1]

Counting down from n

The classic variant:

function countdown(n) {
  if (n < 0) return [];
  return [n, ...countdown(n - 1)];
}

console.log(countdown(4)); // [4, 3, 2, 1, 0]

With a step

function rangeStep(start, end, step = 1) {
  if (step <= 0) throw new RangeError('step must be positive');
  if (start > end) return [];
  return [start, ...rangeStep(start + step, end, step)];
}

console.log(rangeStep(0, 10, 2)); // [0, 2, 4, 6, 8, 10]
console.log(rangeStep(1, 2, 5));  // [1]

Validating the step outside the recursion would be better still — the check runs on every frame here. Wrapping the recursive worker in a public function is the usual fix:

function rangeChecked(start, end, step = 1) {
  if (step <= 0) throw new RangeError('step must be positive'); // once
  const walk = (from) => (from > end ? [] : [from, ...walk(from + step)]);
  return walk(start);
}

console.log(rangeChecked(0, 6, 3)); // [0, 3, 6]

The ways you would actually write it

const n = 5;

console.log(Array.from({ length: n }, (_, i) => i + 1));          // [1,2,3,4,5]
console.log([...Array(n).keys()]);                                 // [0,1,2,3,4]
console.log(Array.from({ length: 4 }, (_, i) => i + 1 + 2));       // [3,4,5,6] — from 3

// Any bounds:
const range = (start, end) =>
  Array.from({ length: end - start + 1 }, (_, i) => start + i);
console.log(range(3, 7)); // [3, 4, 5, 6, 7]

Array.from({ length: n }, fn) is the one to remember: no recursion, no mutation, and it works for any mapping. Note that Array(n).map(…) does not work, because the slots are empty rather than undefined:

console.log(Array(3).map((_, i) => i));               // [empty × 3] — map skips holes
console.log(Array.from({ length: 3 }, (_, i) => i));  // [0, 1, 2]
console.log([...Array(3)].map((_, i) => i));          // [0, 1, 2] — spread fills the holes

Factorial, for completeness

The third member of this family, and the one sum is usually taught next to:

function fact(n) {
  if (n < 0) throw new RangeError('n must be >= 0');
  if (n <= 1) return 1;            // 0! and 1! are both 1
  return n * fact(n - 1);
}

console.log(fact(0), fact(1), fact(5)); // 1 1 120
console.log(fact(21));                   // 51090942171709440000 — already imprecise
console.log(2n ** 64n);                  // BigInt, when exactness matters

fact(21) exceeding Number.MAX_SAFE_INTEGER is a good detail to mention unprompted: past 2^53 the result is a rounded double, and BigInt is the fix.

function factBig(n) {
  return n <= 1n ? 1n : n * factBig(n - 1n);
}
console.log(factBig(21n)); // 51090942171709440000n — exact

Common mistakes

A base case the input can step over

Mistake. if (n === 0) in sum, called with a negative number or stepping by 2. Why it fails. The input passes straight through the exact value and recurses without end. What to do instead. if (n <= 0), so the base case is a boundary.

Spreading the tail on every call

Mistake. const [first, ...rest] = arr inside the recursion over a large array. Why it fails. Every frame copies the remaining elements, so an O(n) walk does O(n²) work. What to do instead. Pass an index, or use reduce.

Expecting a tail call to be free

Mistake. Rewriting a deep recursion with an accumulator to avoid a stack overflow. Why it fails. V8 does not implement tail-call optimisation, so the frame count is unchanged. What to do instead. Use a loop when the depth scales with the input size. Keep recursion for data whose depth is bounded by its shape.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

Each call waits for the one it made, so the multiplying happens on the way back out.

What does this log?

Code sample
function fact(n) {
  if (n <= 1) return 1;
  return n * fact(n - 1);
}

console.log(fact(4));

A range built by recursion grows out of the result the smaller call returned.

What does this log?

Code sample
function range(start, end) {
  if (start > end) return [];
  return [start, ...range(start + 1, end)];
}

console.log(range(1, 4));

What does memoising a recursive function change?

Practise Recursion →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.