Skip to content

Tail Call Optimization

Spicy — senior dev territoryGeneral Dev

ELI5 — The Vibe Check

Tail call optimization is when the compiler realizes your recursive function's last action is calling itself, so instead of stacking calls until the stack explodes, it just reuses the current frame. It's recursion without the stack overflow — infinite loops, responsibly.

Real Talk

A compiler optimization that reuses the current function's stack frame when the last operation is a function call (tail position), converting recursion into iteration. TCO prevents stack overflow for recursive algorithms and is guaranteed in some languages (Scheme, Erlang) but not in most JavaScript engines despite being in the ES6 spec.

Show Me The Code

// Not tail-recursive (stack grows)
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1); // multiplication AFTER call
}

// Tail-recursive (can be optimized)
function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, n * acc); // call IS last operation
}

When You'll Hear This

"Rewrite it as tail-recursive so the compiler can optimize it into a loop." / "Only Safari implements TCO for JavaScript — every other engine just ignores the spec."

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