Problem Solving Fundamentals · Recursion

Carry the answer with you

tail recursion

Carry the answer with you

You are adding a long column of numbers aloud. Say the running total after each one, and you never have to remember the numbers behind you — the tally on the clipboard holds them. When you reach the bottom, the number on the clipboard is the answer, and nothing is left to do on the way back up.

That is the shape of a tail call. A call sits in tail position when its result is returned straight away, with no work left after it returns. return sum(rest, running + first) is a tail call: the addition happens before the call, and its result becomes the function's result. return first + sum(rest) is not — that addition waits for the call to come back.

The accumulator pattern puts the running total in an argument, exactly like the clipboard. Start it at the identity — 0 for a sum — and carry it forward on every call.

You still need a base case: the empty list, where the accumulator already holds the answer. Shrink the list each time, and trust that the smaller call carries the tally the rest of the way.

function sum(numbers, running) {
  if (numbers.length === 0) {
    return running;
  }

  return sum(numbers.slice(1), running + numbers[0]);
}

It is tempting to think a tail call reuses one frame and never runs out of room. JavaScript engines do not promise that. V8 keeps a frame per call, so a deep tail recursion still overflows the stack. Treat the accumulator as a clear way to write the loop, not a guarantee the engine folds it away.

You are about to answer a quiz on tail recursion.

  1. A call in tail position returns its result directly, with no work left to do after it returns.
  2. Carrying a partial result forward in an argument is the ___ pattern.
  3. In `return first + sum(rest)`, the call to `sum` is a tail call.
  4. A sum accumulator starts at the identity value ___.
  5. JavaScript engines reliably reuse the stack frame for a tail call, so a deep tail recursion never overflows.
  6. V8 keeps a stack ___ per call, so a deep tail recursion can still overflow.