Skip to content
jshacks.dev
Fundamentals

Tail Calls Recursion Limits and the Call Stack in JavaScript

Engines cap recursion depth, so deep recursion throws a RangeError, and tail call optimization will not save you. See how to measure depth and use loops.

7 min read
Summarize in AI
Flat illustration of shipping containers stacked on a ship, with the JavaScript, NGINX, Kubernetes and Terraform logos.

A function that calls itself is the natural way to write a sum, a factorial, a tree walk or a parser, and it works until the day the input is large. Then RangeError: Maximum call stack size exceeded appears, and the code that passed every test falls over in production on a long list or a deeply nested document. The error is not a bug in the algorithm. It is the engine telling you that every call takes a slot in a stack of fixed size and the stack is full. This post shows what limits recursion, how to measure the limit on your runtime without guessing, why tail call optimization is not the escape it looks like, and the three practical fixes: a loop, an explicit stack and a trampoline. Output is from Node.js 24 as an ES module. The stack itself is explained in the post on JavaScript engines, and the memory side in the post on memory management.

The error

A recursive sum is correct and has a limit.

JavaScript
function sumTo(n) {
  return n === 0 ? 0 : n + sumTo(n - 1);
}

console.log(sumTo(1000));
console.log(sumTo(5000));

try {
  console.log(sumTo(1_000_000));
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
500500
12502500
RangeError: Maximum call stack size exceeded

A thousand levels and five thousand levels worked. A million failed with a RangeError, and the engine unwound the stack so that the program could continue, which is why the catch ran. The limit is not a property of the language. It is a property of the engine, its stack size and the size of each frame.

Measuring the limit

You can count how deep a runtime lets you go. The number varies with the machine and the function, so use it as an order of magnitude and not as a constant.

JavaScript
function depth() {
  let reached = 0;

  function recurse() {
    reached += 1;
    recurse();
  }

  try {
    recurse();
  } catch (error) {
    return reached;
  }
}

const small = depth();

function depthWithLocals() {
  let reached = 0;

  function recurse(a, b, c, d, e, f) {
    const x = a + b + c;
    const y = d + e + f;
    reached += 1;
    return recurse(x, y, a, b, c, d) + x + y;
  }

  try {
    recurse(1, 2, 3, 4, 5, 6);
  } catch (error) {
    return reached;
  }
}

const bigger = depthWithLocals();

console.log(small > 1000, small < 1_000_000);
console.log(bigger > 1000, bigger < small);
Text
true true
true true

Both limits are in the thousands to tens of thousands, and the function with six parameters and locals reached less than the bare one, because each of its frames is larger. The exact values change between versions and platforms, so a test that asserts a specific depth will break. Design for a margin: if your data can recurse more than a few thousand levels, treat recursion as unsafe.

Tail calls do not save you

A tail call is a call that is the last thing a function does. A language with tail call optimization reuses the frame for it, so a tail-recursive function runs in constant stack space. The ES2015 specification requires this, and in practice only Safari's engine implements it. V8 and SpiderMonkey chose not to, mainly because it makes stack traces incomplete.

JavaScript
function sumTail(n, accumulator = 0) {
  if (n === 0) return accumulator;
  return sumTail(n - 1, accumulator + n);
}

console.log(sumTail(1000));

try {
  console.log(sumTail(1_000_000));
} catch (error) {
  console.log(error.name);
}
Text
500500
RangeError

The tail-recursive version has the right shape, with the recursive call in tail position, and in Node.js it still overflows. Writing code in this style and hoping for optimization is a bug waiting for a different engine. In a browser that must support more than one, or a server on V8, convert it.

Fix one: a loop

Most recursion over a number or a list is a loop in disguise. Rewriting it removes the limit.

JavaScript
function sumLoop(n) {
  let total = 0;
  for (let i = 1; i <= n; i++) total += i;
  return total;
}

console.log(sumLoop(1_000_000));

function factorial(n) {
  let result = 1n;
  for (let i = 2n; i <= n; i++) result *= i;
  return result;
}

console.log(factorial(25n));
console.log(factorial(2000n).toString().length);
Text
500000500000
15511210043330985984000000n
5736

A loop has no depth. The factorial of 2000 is computed without trouble, with bigint supplying the size. When a recursive definition is the clearest statement of a problem, keep it for small inputs and put a loop behind the public function for large ones.

Fix two: an explicit stack

Trees and graphs are where recursion is natural and where depth is least predictable, because a malicious or unlucky input can be deeply nested. An explicit stack in a loop keeps the traversal order and removes the limit.

JavaScript
function makeChain(depth) {
  let node = { value: depth, children: [] };
  for (let i = depth - 1; i >= 1; i--) {
    node = { value: i, children: [node] };
  }
  return node;
}

function sumRecursive(node) {
  return node.value + node.children.reduce((sum, child) => sum + sumRecursive(child), 0);
}

function sumIterative(root) {
  let total = 0;
  const stack = [root];

  while (stack.length > 0) {
    const node = stack.pop();
    total += node.value;
    for (const child of node.children) stack.push(child);
  }

  return total;
}

const shallow = makeChain(100);
const deep = makeChain(200_000);

console.log(sumRecursive(shallow), sumIterative(shallow));
console.log(sumIterative(deep));

try {
  sumRecursive(deep);
} catch (error) {
  console.log(error.name);
}
Text
5050 5050
20000100000
RangeError

Both versions agree on the shallow chain. The iterative one handled a chain of 200,000 nodes, and the recursive one overflowed. The explicit stack holds nodes on the heap, which is limited by memory and not by the call stack. The visit order is depth-first in both, although a stack pops the last child first. Push children in reverse if the order matters, or use a queue for breadth-first.

A generator can also walk a structure lazily, yielding nodes one at a time, as in the post on iterators and iterables, though a recursive generator brings the stack limit back. Functions that process nested structure inherit the same limit. JSON.stringify and JSON.parse on very deep input throw the same error, and so do naive deep clones and equality checks, which is a reason to cap nesting depth when you accept data from outside.

Fix three: a trampoline

A trampoline keeps the recursive definition and runs it in a loop. Each step returns a function, a thunk, that represents the next call, and a driver calls thunks until a value comes back.

JavaScript
function trampoline(fn) {
  return (...args) => {
    let result = fn(...args);
    while (typeof result === "function") result = result();
    return result;
  };
}

const sum = trampoline(function step(n, accumulator = 0) {
  if (n === 0) return accumulator;
  return () => step(n - 1, accumulator + n);
});

console.log(sum(1_000_000));

const parity = trampoline(function check(n, wantEven = true) {
  if (n === 0) return wantEven;
  return () => check(n - 1, !wantEven);
});

console.log(parity(100_000), parity(100_001));
Text
500000500000
true false

The tail-recursive sum ran a million steps in constant stack space, because each step returned a thunk and the driver called it. The second example folds a two-function recursion, is-even and is-odd, into one trampolined function that flips a flag at each step, so the whole thing runs in constant stack. Mutual recursion between two separately trampolined functions needs more care, and a loop or a state machine is usually cleaner there. A trampoline allocates a closure per step, so it trades stack for garbage, and a loop is still faster where it applies.

Async recursion and the event loop

Recursion through promises and timers does not grow the call stack, because each step starts in a fresh turn of the event loop.

JavaScript
async function countDown(n) {
  if (n === 0) return "done";
  await null;
  return countDown(n - 1);
}

console.log(await countDown(50_000));

let ticks = 0;

function tick(n, done) {
  ticks += 1;
  if (n > 0) setImmediate(() => tick(n - 1, done));
  else done(ticks);
}

console.log(await new Promise((resolve) => tick(50_000, resolve)));
Text
done
50001

An async recursion of fifty thousand levels completed, because each await yields to the scheduler. It does build a chain of promises in memory, so its limit is memory and not stack. A recursion driven by setImmediate also stays flat, and the promise resolves when the last step has run, so the printed count is exact. This is the escape for work that can be asynchronous, and it is also how long computations are split to keep a page responsive, a technique covered in the performance topic.

Changing the stack size

Node.js accepts --stack-size to raise the limit, and it is tempting. The flag sets a number V8 uses to decide when to throw, but the operating system's real stack for the main thread is fixed, so a value above what the OS provides crashes the process with a segmentation fault instead of throwing. Treat it as a diagnostic for a specific script and not a production setting. Worker threads accept a resourceLimits.stackSizeMb option that is safer, since the engine allocates that stack.

Where recursion is still the right tool

For bounded depth, recursion is the clearest code: a tree of a known small height, a parser for input you control, a divide-and-conquer sort that halves the problem so that depth is logarithmic. Merge sort recursing on 10 million items goes about 24 levels deep and never threatens the stack. The danger is recursion whose depth grows with the input size, a list of unknown length or a nesting you do not control.

The rule we apply is to ask what the deepest input is. If the answer is "a few hundred", recurse. If it is "whatever the user sends", loop.

The tail position is defined in the specification under tail position calls, and MDN's page on RangeError describes the error and the usual causes.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.