← JavaScript

Intermediate · 15 of 17 · 19 min read

Recursion

The base case and the recursive case, how to read a call trace, and the depth limit that decides when a loop is the safer choice.

  • Recursion

A recursive function solves a problem by calling itself on a smaller version of the same problem. Every working one has exactly two parts, and naming them is how you write one without getting lost.

The two parts

function countdown(n) {
  if (n === 0) return ['liftoff'];  // base case
  return [n, ...countdown(n - 1)];  // recursive case: n - 1 moves towards 0
}

console.log(countdown(3)); // [3, 2, 1, "liftoff"]

What goes wrong when a part is missing:

// No base case at all:
function forever(n) {
  return forever(n - 1); // RangeError: Maximum call stack size exceeded
}

// A base case that is never reached:
function missed(n) {
  if (n === 0) return 0;
  return missed(n - 2); // from an odd n, it steps straight past 0
}
// missed(5); // RangeError — 5, 3, 1, -1, -3, …

The second one is the subtler bug and the more common one in real code: there is a base case, but some inputs never land on it. if (n <= 0) instead of if (n === 0) fixes this instance, and the general habit is to make the base case a boundary, not an exact value.

Reading a trace

Nothing is computed on the way down. The answers appear as the stack unwinds:

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

console.log(fact(4)); // 24
fact(4) → 4 * fact(3)
          fact(3) → 3 * fact(2)
                    fact(2) → 2 * fact(1)
                              fact(1) → 1        ← base case, the first real value
                    fact(2) → 2 * 1  = 2
          fact(3) → 3 * 2  = 6
fact(4) → 4 * 6  = 24
fact(4) stepped through: four frames pushed with pending multiplications, the base case answering first, and each multiplication completing on the way back up.
Call stackfact(4)4 * ?4 * 6 = 24fact(3)3 * ?3 * 2 = 6fact(2)2 * ?2 * 1 = 2fact(1)base casereturns 1Returnsfact(1) → 1fact(2) → 2fact(3) → 6fact(4) → 24callsreturns

6 fact(4) is called. 4 is not the base case, so it cannot return anything until it knows fact(3) — the multiplication is left pending.

3 Down one, same situation. A second pending multiplication, waiting on a smaller call.

3 And again. Three frames, three pending multiplications, zero answers so far.

2 fact(1) hits the base case: the first call that can answer without recursing, and the first real value in the run.

3 Now it unwinds. fact(2) finally has what it was waiting for and completes its multiplication.

3 3 * 2. Each frame had been holding its own n the whole time — that is what made this possible, and what it cost.

3 4 * 6 = 24. The last frame pops and the stack is empty. Every multiplication happened on the way back up.

Nothing is computed on the way down — steps 1 to 3 produce no answers at all, only pending work. That is the difference between recursion and a loop: the loop keeps one running total in one variable, and the recursion keeps n half-finished multiplications, one per frame.

Logging both directions makes it concrete:

function fact(n, depth = 0) {
  console.log(' '.repeat(depth) + 'down ' + n);
  if (n <= 1) return 1;
  const result = n * fact(n - 1, depth + 1);
  console.log(' '.repeat(depth) + 'up   ' + n + ' -> ' + result);
  return result;
}

fact(3);
// down 3 /  down 2 /   down 1 /  up   2 -> 2 / up   3 -> 6

Four calls are on the stack at the deepest point. That is the cost recursion pays and a loop does not.

Where recursion earns its place

Not for counting — a loop is clearer there. For data whose shape is nested and whose depth you do not know.

Walking a tree

const tree = {
  name: 'root',
  children: [
    { name: 'a', children: [{ name: 'a1', children: [] }] },
    { name: 'b', children: [] },
  ],
};

function names(node) {
  return [node.name, ...node.children.flatMap(names)];
}

console.log(names(tree)); // ["root", "a", "a1", "b"]

The iterative version needs an explicit stack of pending nodes — which is the call stack, written out by hand:

function namesIterative(root) {
  const out = [];
  const pending = [root];
  while (pending.length > 0) {
    const node = pending.pop();
    out.push(node.name);
    pending.push(...node.children);
  }
  return out;
}
console.log(namesIterative(tree).length); // 4 — same nodes, different order

Both are valid. The recursive one is four lines and matches the data; the iterative one cannot blow the stack. That is the whole trade-off, and it is worth being able to state it cleanly:

Recursion Loop
Memory for depth n O(n) — one frame per level O(1)
Can overflow the stack yes no
Nested data of unknown depth natural needs your own stack
A flat, known range more code simpler
Where the state lives the call frames variables you manage

Summing an object of unknown depth

const data = { a: 1, b: { c: 2, d: { e: 3 } } };

function sumValues(node) {
  return Object.values(node).reduce(
    (total, value) => total + (typeof value === 'object' && value !== null ? sumValues(value) : value),
    0,
  );
}

console.log(sumValues(data)); // 6

Flattening

function flatten(arr) {
  return arr.reduce(
    (out, item) => (Array.isArray(item) ? [...out, ...flatten(item)] : [...out, item]),
    [],
  );
}

console.log(flatten([1, [2, [3, [4]]]])); // [1, 2, 3, 4]
console.log([1, [2, [3, [4]]]].flat(Infinity)); // the built-in does the same

Halving the input is the textbook “smaller problem”:

function search(sorted, target, low = 0, high = sorted.length - 1) {
  if (low > high) return -1;                 // base case: nothing left
  const mid = Math.floor((low + high) / 2);
  if (sorted[mid] === target) return mid;
  return sorted[mid] < target
    ? search(sorted, target, mid + 1, high)  // half the range
    : search(sorted, target, low, mid - 1);
}

console.log(search([1, 3, 5, 7, 9], 7)); // 3
console.log(search([1, 3, 5, 7, 9], 4)); // -1

The depth limit

Each pending call keeps a frame on the stack, and the stack is finite — around 10,000 frames in most engines, though the exact number depends on the engine and on how many locals each frame holds.

function depth(n = 0) {
  try {
    return depth(n + 1);
  } catch {
    return n; // roughly where this engine gives up
  }
}
console.log(depth() > 5000); // true

JavaScript specifies tail-call optimisation but almost no engine implements it, so writing a tail-recursive function does not raise the limit:

function sumTail(n, acc = 0) {
  if (n === 0) return acc;
  return sumTail(n - 1, acc + n); // a tail call, and the frame is still kept
}
// sumTail(100000); // RangeError in V8 anyway

So the rule for production code is: recursion when the depth is bounded by the shape of the data — a DOM tree, a directory, a JSON document, all a few dozen deep at worst. A loop when the depth is bounded by the size of the data.

// Depth grows with n: 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 — no stack involved

Recursion with memory

Naive Fibonacci recomputes the same inputs an exponential number of times:

let calls = 0;
function fib(n) {
  calls += 1;
  return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}
console.log(fib(20), calls); // 6765 21891 — for a single answer

A cache turns the exponential tree into a linear walk:

function fibMemo(n, cache = new Map()) {
  if (n <= 1) return n;
  if (cache.has(n)) return cache.get(n);
  const value = fibMemo(n - 1, cache) + fibMemo(n - 2, cache);
  cache.set(n, value);
  return value;
}

console.log(fibMemo(50)); // 12586269025 — instant
// fib(50) would take days

Memoising only helps when the recursion revisits the same input. Walking a tree never does, so a cache there is pure overhead.

Mutual recursion

Two functions that call each other — rare, but it appears in parsers and in this classic:

const isEven = (n) => (n === 0 ? true : isOdd(n - 1));
const isOdd = (n) => (n === 0 ? false : isEven(n - 1));

console.log(isEven(10), isOdd(7)); // true true

Common mistakes

A base case some inputs skip

Mistake. if (n === 0) in a function that steps by 2, or that can be called with a negative number. Why it fails. The input jumps over the exact value and recurses forever. What to do instead. Make it a boundary: if (n <= 0).

Recursing on the same input

Mistake. return walk(node) instead of return walk(node.next). Why it fails. The input never shrinks, so the base case is never closer — the commonest cause of an accidental infinite recursion. What to do instead. Before writing the recursive call, say out loud what is smaller about its argument.

Forgetting to return the recursive call

Mistake. fact(n - 1) on its own line, with no return. Why it fails. The inner result is computed and discarded, so the function returns undefined and the arithmetic above it produces NaN. What to do instead. Return the recursive call — or assign it to a variable you then use.

function broken(n) {
  if (n <= 1) return 1;
  n * broken(n - 1); // computed, thrown away
}
console.log(broken(4)); // undefined

Check yourself

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

What two parts does every working recursive function have?

This is meant to count down to zero and stop, but the engine gives up first.

Why does this throw RangeError: Maximum call stack size exceeded?

Code sample
function countdown(n) {
  console.log(n);
  countdown(n - 1);
}

countdown(3);

When is recursion the better choice than a loop?

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.