Recursion is lying to you
a day ago
- Recursion is elegant for naturally recursive problems (tree walks, divide-and-conquer) but each call consumes stack space, leading to stack overflow at large depths.
- Tail call optimization (TCO) can theoretically reuse stack frames, but JavaScript runtimes rarely implement it reliably; even correctly tail-recursive code may still overflow.
- The Fibonacci example shows that exponential branching and stack overflow are distinct failure modes, requiring different fixes.
- A table of runtime TCO support (May 2026) shows that Chrome/V8, Node.js, Deno, Firefox, Safari, and Bun all lack reliable TCO, so portability cannot be assumed.
- Production-safe alternatives include iterative rewriting and the trampoline pattern, which maintains recursive style while avoiding stack growth.
- Practical checklist: never assume TCO, test with realistic bounds, favor iteration for deep or user-driven input, and treat recursion as a readability tool only for bounded depths.