Hint
A tail call is the last operation in a function β engine can reuse the stack frame instead of adding a new one
A tail call is when the last action of a function is calling another function. If the engine applies TCO, it reuses the current stack frame instead of pushing a new one β preventing stack overflow for deep recursion.
// Regular recursion β O(n) stack frames
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1); // NOT tail call β must multiply AFTER return
}
factorial(100000); // Stack overflow!
// Tail-recursive version β last op is the call
function factTail(n, accumulator = 1) {
if (n <= 1) return accumulator;
return factTail(n - 1, n * accumulator); // tail call β nothing after it
}
// With TCO, this would run in O(1) stack space
// Current reality:
// TCO is in the ES6 spec BUT only Safari implements it fully
// V8 (Node/Chrome) removed their TCO implementation
// So tail recursion is NOT safe in Node.js / Chrome!
// Practical alternatives:
// 1. Iteration (always safe)
function factIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) result *= i;
return result;
}
// 2. Trampolining β simulates TCO in user space
const trampoline = fn => (...args) => {
let result = fn(...args);
while (typeof result === 'function') result = result();
return result;
};
const factTramp = trampoline(function fact(n, acc = 1) {
return n <= 1 ? acc : () => fact(n - 1, n * acc); // return fn instead of calling
});
factTramp(100000); // works!