What is tail call optimization?
Answer
Tail call optimization (TCO) is a specification-level optimization where a function call in the "tail position" (the very last action of a function) does not need to add a new frame to the call stack. In strict mode ES6, if the last thing a function does is call another function and return its result directly, the engine can reuse the current stack frame instead of creating a new one. This allows recursive functions to run without stack overflow risk — O(1) stack space instead of O(n). A tail call: "use strict"; function factorial(n, acc = 1) { if (n <= 1) return acc; return factorial(n - 1, n * acc); // tail call }. Non-tail call: return n * factorial(n - 1) — cannot be optimized because multiplication happens AFTER the recursive call. Caveat: as of 2024, only JavaScriptCore (Safari) implements TCO from the ES6 spec. V8 (Chrome/Node) dropped it due to tooling issues. TCO remains important conceptually and is fully implemented in some environments.