Skip to content

Tail Call

Medium — good to knowlanguages

ELI5 - The Vibe Check

A tail call is when a function's very last action is to call another function and immediately return whatever that call gives back, nothing left to do afterward. Some languages notice this pattern and reuse the current function's stack space instead of piling a new frame on top, which means a recursive function written as a tail call can loop forever without ever blowing the stack, in languages that actually bother to optimize for it.

Real Talk

A tail call occurs when a function's final action is invoking another function and immediately returning its result with no further computation. Tail call optimization (TCO) lets a compiler or runtime reuse the current stack frame for the called function instead of pushing a new one, turning tail-recursive functions into effectively constant-stack-space loops. Languages like Scheme guarantee TCO, while others, including Python and most JavaScript engines, do not.

Show Me The Code

// Tail-recursive: the recursive call is the last thing that happens
function sum(n, acc = 0) {
  if (n === 0) return acc;
  return sum(n - 1, acc + n); // tail call
}

When You'll Hear This

"Rewrite it as a tail call so it doesn't blow the stack on deep recursion." / "Don't count on tail call optimization in JavaScript, most engines don't actually do it."

Made with passive-aggressive love by manoga.digital. Powered by Claude.