MediumFunctions📖 Theory Question

What is tail call optimization (TCO) and how does it prevent stack overflow?

💡

Hint

A tail call is the last operation in a function — engine can reuse the stack frame instead of adding a new one

Full Answer

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!
💡 Know the theory for interviews but use iteration in production. Trampolining is the practical way to handle very deep recursion in JS without relying on TCO.

More Functions Questions

EasyWhat is the difference between call, apply, and bind?EasyHow do arrow functions differ from regular functions?EasyWhat is a pure function and why does it matter?EasyWhat are Higher-Order Functions (HOF)?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint