Tail Call Optimization
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."
Related Terms
Compiler
A compiler is like a translator that reads your entire code book, converts it all into a language the CPU understands, and hands you the finished translate...
Functional Programming
Functional programming is like cooking with strict rules: no shared bowls, no side dishes contaminating each other, and every dish must be exactly reproduc...
Recursion
Recursion is when a function calls itself to solve a smaller version of the same problem, like a set of Russian nesting dolls.
Stack Overflow
A stack overflow happens when a function keeps calling itself forever, like a mirror facing a mirror.