Skip to content

Tail Call Optimization

In one line

Tail call optimization (TCO) reuses the current stack frame when a function's last action is a recursive call, preventing stack overflow.

In simple words

Tail call optimization is a compiler/interpreter technique where, if a function's very last action is to call itself (a tail call), the engine reuses the current stack frame instead of pushing a new one. This means a recursive function can loop indefinitely without growing the call stack or causing a stack overflow.

A tail call is when the recursive call is the final operation and its result is returned directly — no work is done after the call returns. For example, return factorial(n-1) * n is NOT a tail call (the multiply happens after), but return helper(n-1, acc * n) IS a tail call because the helper call is the last thing.

Not all languages support TCO: JavaScript specifies it but most engines (except Safari's JavaScriptCore) do not implement it. Scheme, Haskell, and Lua guarantee TCO. When TCO is unavailable, deep recursion still overflows the stack, and you must rewrite the recursion as a loop or use a trampoline.

Example

javascript
// Tail-recursive factorial — accumulator makes the call tail
function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, acc * n); // tail call — last action
}

console.log(factorial(5)); // 120
// factorial(5,1) → factorial(4,5) → factorial(3,20) → factorial(2,60) → factorial(1,120) → 120

By carrying the accumulator, the recursive call is the very last operation. A TCO-capable engine reuses the stack frame.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary