← Back to JavaScript, page 4

javascript-0072 · Medium mid

How do you avoid stack overflow in deep recursion, and what happens with tail call optimization in JavaScript?

Each recursive call uses a stack frame, so very deep recursion throws a RangeError. A tail call is a call in return position, and the language specification allows reusing the frame, but only Safari implements it, so JavaScript code cannot rely on it. Practical fixes are a loop, an explicit stack, or a trampoline that returns thunks instead of calling itself.

Full answer

The call stack has a fixed size. A recursive function that goes tens of thousands of levels deep, such as summing a long linked list, throws RangeError: Maximum call stack size exceeded, even though the logic is correct. The exact depth depends on the engine and on how much each frame stores.

A tail call is a function call that is the last thing a function does, as in return sum(n - 1, total + n). Because nothing is left to do after the call returns, an engine could replace the current frame with the new one and use constant stack space. ES2015 standardized this proper tail call behavior. In practice, only Safari (JavaScriptCore) implements it. V8 and SpiderMonkey chose not to, partly for debugging reasons, so portable code must not depend on it.

Reliable alternatives:

  • Rewrite as a loop. This is the simplest fix for linear recursion such as sums and counters.
  • Use an explicit stack (an array) for tree and graph traversals. The function keeps its own list of work, so depth is limited by memory, not by the call stack.
  • Use a trampoline. The recursive function returns a function (a thunk) describing the next step instead of calling itself. A small loop keeps running thunks until a real value appears. Stack depth stays constant at the cost of some allocation.
  • Reduce the depth with a better algorithm, such as divide and conquer.

Mutual recursion and deep recursion on user-controlled input are also a risk: a crafted deeply nested input can crash a parser, so bound the depth.

javascript
function sumRecursive(n) {
  return n === 0 ? 0 : n + sumRecursive(n - 1);
}
try {
  console.log(sumRecursive(1000));
  console.log(sumRecursive(200000));
} catch (error) {
  console.log('deep recursion:', error.name);
}

function sumTail(n, total = 0) {
  return n === 0 ? total : sumTail(n - 1, total + n); // a tail call, not optimized in Node.js
}
try {
  console.log(sumTail(200000));
} catch (error) {
  console.log('tail call without optimization:', error.name);
}

function trampoline(fn) {
  return (...args) => {
    let result = fn(...args);
    while (typeof result === 'function') result = result();
    return result;
  };
}
const sumTrampolined = trampoline(function step(n, total = 0) {
  return n === 0 ? total : () => step(n - 1, total + n);
});
console.log(sumTrampolined(200000));

const sumLoop = (n) => {
  let total = 0;
  for (let i = 1; i <= n; i++) total += i;
  return total;
};
console.log(sumLoop(200000));

function buildNested(depth) {
  let node = { value: 0, children: [] };
  const root = node;
  for (let i = 1; i < depth; i++) {
    const child = { value: i, children: [] };
    node.children.push(child);
    node = child;
  }
  return root;
}
function maxDepthRecursive(node) {
  return 1 + Math.max(0, ...node.children.map(maxDepthRecursive));
}
function maxDepthIterative(root) {
  let deepest = 0;
  const stack = [[root, 1]];
  while (stack.length) {
    const [node, depth] = stack.pop();
    deepest = Math.max(deepest, depth);
    for (const child of node.children) stack.push([child, depth + 1]);
  }
  return deepest;
}
const tree = buildNested(50000);
try {
  maxDepthRecursive(tree);
} catch (error) {
  console.log('recursive traversal:', error.name);
}
console.log('explicit stack:', maxDepthIterative(tree));

Run with Node.js v24.22.1 as js-72.js; two runs gave identical output. Output: 500500 deep recursion: RangeError tail call without optimization: RangeError 20000100000 20000100000 recursive traversal: RangeError explicit stack: 50000

Key points

  • Deep recursion throws RangeError because the call stack is limited.
  • A tail call is the last action of a function; the spec allows frame reuse, but only Safari implements it.
  • Loops and explicit stacks are the reliable fixes.
  • A trampoline returns thunks and a loop runs them, keeping the stack flat.
  • Limit recursion depth on untrusted nested input.

Common mistakes

  • Relying on tail call optimization in code that runs in Node.js or Chrome.
  • Using recursion for traversing very deep or user-supplied structures without a depth limit.
  • Using a trampoline for a function that returns a function as its real result, which the loop would keep calling.
  • Raising the stack size with engine flags instead of fixing the algorithm.

Follow-ups

  • How would you convert a recursive depth-first search into an iterative one?
  • Why did some engines decline to implement proper tail calls?
  • How does JSON.parse handle very deeply nested input?

Tips

  • State clearly that tail calls are standardized but not portable.
  • Offer the three fixes in order: loop, explicit stack, trampoline.
  • Mention untrusted nested input as a real-world cause.