TryBugHunt

RangeError: Maximum call stack size exceeded

RangeError: Maximum call stack size exceeded in JavaScript means a function called itself (directly or through others) with no way to stop. JavaScript's equivalent of infinite recursion.

JavaScriptPattern: Infinite loops

How do I fix RangeError: Maximum call stack size exceeded?

RangeError: Maximum call stack size exceeded means a JavaScript function kept calling itself until the stack ran out. The base case is missing or never reached, a setter assigns to its own property, or a huge array was spread into Math.max(...arr). Fix the base case to use n <= 0, store setter values in _name, or use reduce.

  1. 1. Read the stack traceLook for the same function names repeating. That repeating group is the cycle.
  2. 2. Check the base caseMake sure each call moves toward the base case, and the input that crashed can reach it.
  3. 3. Check setters and spreadsthis.name = v inside set name() calls itself. Math.max(...bigArray) overflows on very large arrays.

What does RangeError: Maximum call stack size exceeded mean?

Every call adds a frame to the call stack; the stack has a fixed size, roughly ten thousand frames depending on the engine. Recursion that never reaches its base case fills it. The stack trace repeats the same few function names — those are your loop.

Why does RangeError: Maximum call stack size exceeded happen?

1. A recursive function with no reachable base case

The base case exists, but the recursive call never moves towards it.

Breaks

function countdown(n) {
  if (n === 0) return;
  countdown(n);
}

Works

function countdown(n) {
  if (n <= 0) return;
  countdown(n - 1);
}

2. A setter that assigns to itself

this.name = v inside set name() calls the setter again, forever.

Breaks

class User {
  set name(v) { this.name = v.trim(); }
}

Works

class User {
  set name(v) { this._name = v.trim(); }
  get name() { return this._name; }
}

3. Spreading a huge array into a call

Every element becomes an argument; past about a hundred thousand, the call itself overflows.

Breaks

const max = Math.max(...bigArray);

Works

const max = bigArray.reduce((m, x) => (x > m ? x : m), -Infinity);

How to find it in your own code

Open the stack trace and find the repeating pair or trio of function names — that is the cycle. Check the base case is reachable for the input that crashed (negative numbers and non-integers are the usual escapes). For very deep but correct recursion, rewrite it as a loop.

Practise infinite loops

None of the challenges raises this exact error yet. These practise the same kind of bug.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all infinite loops →