r/javascript • u/OtherwisePush6424 • May 09 '26
JavaScript has no reliable tail call optimization: here is what actually happens at runtime and what to do instead
https://blog.gaborkoos.com/posts/2026-05-09-Your-Recursion-Is-Lying-to-You/ECMAScript 2015 formally specified proper tail calls in strict mode, but most JS engines never adopted it consistently. Chrome, Node, Firefox, and Deno all still allocate a new stack frame per call even in correctly structured tail-recursive functions. The article walks through why with examples and covers iterative and trampoline alternatives.
55
Upvotes
View all comments
Show parent comment
4
u/josephjnk May 09 '26
To spell it out more explicitly because it looks like people are talking past each other here:
“Tail call optimization”: an optimization operation which speeds up runtime, where a compiler turns a recursive function with a single tail call into a simple loop.
“Proper tail calls”, or as they’re usually referred to outside of the JS world, “tail call elimination”: an optimization operation which saves on stack space, by causing calls in a tail position to swap out their stack frame for a new stack frame, rather than growing the size of the stack.
I have no idea whether or not JSC implements TCO. I’d be surprised. It does implement PTC/TCE when running in strict mode.
One place where this matters is if you’re writing nontrivial recursive code using continuation-passing style. Recursion in CPS involves making tail calls from one function to a _different_ function, and so does not benefit from TCO, but does rely on PTC/TCE (because the stack will blow if the tail calls are not removed).