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.