More JavaScript answers

by Danny
Published 2 min read

This error means a function kept calling itself, directly or indirectly, until the engine ran out of stack. Learn how to find the loop and fix the recursion.

The short answer

#

Something is calling itself with no way to stop, so the call stack fills up. Usually it is a recursive function missing a base case, a setter or getter that calls itself, or two functions that call each other. Find the repeating frames in the stack trace and add a stopping condition or break the cycle.


_10
function countdown(n) {
_10
+ if (n < 0) return; // base case
_10
console.log(n);
_10
countdown(n - 1);
_10
}

Why it happens

#

Every function call adds a frame to the call stack, and the frame is removed when the function returns. The engine sets a limit on how deep the stack can grow. When a chain of calls never returns, the stack hits that limit and the engine throws a RangeError.

The exact limit depends on the engine and on how much each frame holds, so you should not rely on any specific number. Typical causes are:

  • A recursive function with no base case, or a base case that is never reached because the input never changes.
  • A property setter that assigns to the same property, which calls the setter again.
  • Two functions or event handlers that trigger each other, such as a change listener that changes the value it is listening to.
  • Very deep but finite recursion, such as walking a tree or list with tens of thousands of levels.
  • Spreading a very large array into a function call, as in Math.max(...hugeArray), which passes every element as an argument.

How to fix it

#

Read the stack trace

Open the error in DevTools or the Node.js output. The trace shows the same one or two function names repeated many times. Those are the functions in the loop. Put a breakpoint or a console.log at the top of the first one and check whether its arguments move towards the base case.

Add or fix the base case

Make sure the recursion stops and that every call gets closer to stopping.


_10
function sumTree(node) {
_10
if (!node) return 0;
_10
return node.value + sumTree(node.left) + sumTree(node.right);
_10
}

Do not call a setter from itself

Store the value in a different field, such as a private field, so the setter does not trigger itself.


_11
class User {
_11
#name = '';
_11
_11
get name() {
_11
return this.#name;
_11
}
_11
_11
set name(value) {
_11
this.#name = value.trim(); // not this.name = ...
_11
}
_11
}

Break event loops with a guard

If two pieces of code update each other, only update when the value has actually changed.


_10
input.addEventListener('input', () => {
_10
const next = input.value.toUpperCase();
_10
if (input.value !== next) {
_10
input.value = next;
_10
}
_10
});

Replace deep recursion with a loop

For data that can be very deep, use an explicit stack in a loop. It uses heap memory instead of the call stack, so depth is no longer a problem.


_11
function sumTree(root) {
_11
let total = 0;
_11
const stack = [root];
_11
while (stack.length > 0) {
_11
const node = stack.pop();
_11
if (!node) continue;
_11
total += node.value;
_11
stack.push(node.left, node.right);
_11
}
_11
return total;
_11
}

Avoid spreading huge arrays into calls

Use a loop or reduce instead of passing thousands of arguments.


_10
const max = values.reduce((a, b) => (b > a ? b : a), -Infinity);

Common pitfalls

#
  • Relying on tail call optimisation. Most JavaScript engines do not implement it, so tail-recursive code still overflows.
  • Raising the stack size in Node.js with a flag to hide the problem. It only delays the crash and does nothing in the browser.
  • Calling JSON.stringify on an object with a custom toJSON that returns the object itself.
  • Wrapping the call in try...catch and carrying on. The program state is usually wrong by the time the error is thrown.
#

Was this resource helpful?