日本語

How to Fix “Maximum call stack size exceeded” in JavaScript

​​JavaScript​Chromium,Node.js,Troubleshooting

When I ran a recursive function or a class setter, the browser console or the Node.js terminal sometimes showed RangeError: Maximum call stack size exceeded. The function kept calling itself without ever finishing, so the place where calls are stacked up (the call stack) overflowed. Adding a condition that stops the calls, or rewriting the code so it no longer calls itself, makes the error go away.

In my test environment I triggered this error in both Node.js and the browser, and I included the messages exactly as they were printed. I also confirmed that the fixed code no longer throws the error and returns the correct result.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153 (headless) launched with Playwright 1.63.0. In the browser I did not open the DevTools window. Instead, I received what was sent to the console through the DevTools Protocol and displayed it. I used the same JavaScript file for Node.js and the browser. I did not test Firefox or Safari.

Triggering the error with a recursion that has no stop condition

The following bad.js is meant to compute a factorial (5 × 4 × 3 × 2 × 1) recursively. factorial(n) calls factorial(n - 1), but it never says when to stop calling.

js
function factorial(n) {
  return n * factorial(n - 1);
}
console.log("5の階乗:", factorial(5));

When I ran node bad.js in Node.js, the terminal showed the following and stopped (I replaced the file location with /path/to/app).

text
/path/to/app/bad.js:2
  return n * factorial(n - 1);
  ^

RangeError: Maximum call stack size exceeded
    at factorial (/path/to/app/bad.js:2:3)
    at factorial (/path/to/app/bad.js:2:14)
    at factorial (/path/to/app/bad.js:2:14)
    at factorial (/path/to/app/bad.js:2:14)
    at factorial (/path/to/app/bad.js:2:14)
    at factorial (/path/to/app/bad.js:2:14)
    at factorial (/path/to/app/bad.js:2:14)
    at factorial (/path/to/app/bad.js:2:14)
    at factorial (/path/to/app/bad.js:2:14)
    at factorial (/path/to/app/bad.js:2:14)

Node.js v22.23.4

When I opened a page in Chromium that loads the same bad.js with <script src>, the console received the following (I removed the exception: prefix that my test script added to each line). 127.0.0.1:8126 is the HTTP server I started inside the test environment.

text
Uncaught RangeError: Maximum call stack size exceeded
    at factorial (http://127.0.0.1:8126/bad.js:1:19)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)
    at factorial (http://127.0.0.1:8126/bad.js:2:14)

In both cases, the final line of output, the console.log message that prints the factorial result, was never printed.

Maximum call stack size exceeded means "the size limit of the call stack has been exceeded." As the MDN glossary entry for Call stack explains, each time a function is called, it is pushed onto the call stack, and it is removed when the function returns. Because factorial calls the next factorial before it returns, the stack keeps growing, and when it reaches the limit, a RangeError is thrown. The MDN page on "too much recursion" describes this error as occurring when there are too many function calls or when a recursive function has no base case (a condition that stops the recursion). The same page notes that Firefox reports the same cause with a different message: InternalError: too much recursion.

Finding the line that calls itself in the stack trace

The at factorial (...) lines below the error are the stack trace. Every line is factorial. The lines from the second one down all point to bad.js:2:14, which is the factorial(n - 1) call on line 2, column 14 of bad.js. When the same location appears over and over, that is the line that keeps calling itself.

The top line sometimes points to a different location than the repeated lines. In Node.js it was 2:3 (the position of return), and in Chromium it was 1:19 (the position of the ( in the arguments, on the line where the function is declared). Even within the same file, the location differed. Decide where to fix the code by looking at the repeated lines.

Only 10 lines appear because the stack trace shows 10 calls by default. The Node.js documentation for Error.stackTraceLimit states that the default value is 10. In my test environment, node -p Error.stackTraceLimit also returned 10. Even if thousands of calls piled up, only 10 are displayed.

The newest call is at the top. When a called b and b called c, and I printed the stack of an error created inside c in Node.js, the lines appeared in the order at c, at b, at a. This means the 10 lines shown are the most recent 10 calls, right before the overflow.

Adding a stop condition

A recursive function needs a condition that says "return a value now without calling myself again." For a factorial, when n becomes 1 or less, return 1.

js
function factorial(n) {
  if (n <= 1) {
    return 1;
  }
  return n * factorial(n - 1);
}
console.log("5の階乗:", factorial(5));

Node.js and Chromium both ran without an error and printed the following.

text
5の階乗: 120

The stop condition exists, but the value skips past it

Even if you write a stop condition, the same error occurs when the value never exactly matches it. The following countdown is meant to decrease n by 2 each time and print the launch message when n reaches 0.

js
function countdown(n) {
  if (n === 0) {
    console.log("発射!");
    return;
  }
  countdown(n - 2);
}
countdown(5);

Starting from 5, n goes 5, 3, 1, -1, and so on, and never reaches 0. Because n === 0 never becomes true, the calls keep going. In Node.js it printed the following (I replaced the file location).

text
/path/to/app/countdown.js:2
  if (n === 0) {
  ^

RangeError: Maximum call stack size exceeded
    at countdown (/path/to/app/countdown.js:2:3)
    at countdown (/path/to/app/countdown.js:6:3)
    at countdown (/path/to/app/countdown.js:6:3)
    at countdown (/path/to/app/countdown.js:6:3)
    at countdown (/path/to/app/countdown.js:6:3)
    at countdown (/path/to/app/countdown.js:6:3)
    at countdown (/path/to/app/countdown.js:6:3)
    at countdown (/path/to/app/countdown.js:6:3)
    at countdown (/path/to/app/countdown.js:6:3)
    at countdown (/path/to/app/countdown.js:6:3)

Node.js v22.23.4

The repeated countdown.js:6:3 is the countdown(n - 2) call on line 6. When the stop condition uses === to match one exact value, the value can be skipped like this. Use <= so that the function stops once the value is at or below the target.

js

if (n <= 0) {

After changing only this line, there was no error, and the output was:

text
発射!

Assigning to the same property inside a setter

You can get this error even without intending recursion. The following User class tries to trim the leading and trailing spaces from the value assigned to name in its setter.

js
class User {
  set name(value) {
    this.name = value.trim();
  }
  get name() {
    return this.name;
  }
}
const user = new User();
user.name = "  さくら  ";
console.log("名前:", user.name);

In Node.js it printed the following (I replaced the file location).

text
/path/to/app/setter.js:3
    this.name = value.trim();
              ^

RangeError: Maximum call stack size exceeded
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)
    at set name (/path/to/app/setter.js:3:15)

Node.js v22.23.4

at set name means "inside the setter for name." The this.name = ... inside the setter is also an assignment to name, so the same setter is called again. That call runs this.name = ... again, and this continues without end. In the Chromium console, the top line was at String.trim (<anonymous>), followed by a line pointing to the position of trim (setter.js:3:23). Below that, setter.js:3:15 repeated, as in Node.js.

The MDN page on "too much recursion" also includes this setter example and notes that the same problem happens with a getter that does return this.name. The fix is to store the real value somewhere other than name itself. Here I used a private field (#name), which cannot be accessed from outside the class.

js
class User {
  #name = "";
  set name(value) {
    this.#name = value.trim();
  }
  get name() {
    return this.#name;
  }
}
const user = new User();
user.name = "  さくら  ";
console.log("名前:", user.name);

this.#name is a different thing from name, so assigning to it does not call the setter. There was no error, and the trimmed value was printed.

text
名前: さくら

Storing the value in a differently named property, such as this._name as in the MDN example, also stops the setter from calling itself.

The stop condition is correct, but the data is too large

Even with a correct stop condition, this error can occur when the calls go too deep. The following sum adds the numbers in an array one by one from the beginning, using recursion.

js
function sum(numbers, i = 0) {
  if (i === numbers.length) {
    return 0;
  }
  return numbers[i] + sum(numbers, i + 1);
}
const numbers = Array.from({ length: 100000 }, (_, i) => i + 1);
console.log("1000個の合計:", sum(numbers.slice(0, 1000)));
console.log("10万個の合計:", sum(numbers));

The sum from 1 to 1000 printed, but the run stopped while summing from 1 to 100,000 (Node.js output; I replaced the file location. The stack trace shows only the first three lines, and I omitted the remaining seven lines, which were also deep.js:5:23).

text
1000個の合計: 500500
/path/to/app/deep.js:1
function sum(numbers, i = 0) {
            ^

RangeError: Maximum call stack size exceeded
    at sum (/path/to/app/deep.js:1:13)
    at sum (/path/to/app/deep.js:5:23)
    at sum (/path/to/app/deep.js:5:23)

This is because the calls pile up as many times as there are elements in the array. To see how deep a function can go before it overflows, I counted with a function that only calls itself. In the Node.js test environment, it stopped at call number 12,557. In Chromium, it stopped at 19,228 and at 17,824 on different runs, so the number changed each time. The limit depends on the environment, so avoid processing tens of thousands of items with recursion.

You can rewrite this kind of processing with a loop such as for, so that the calls do not pile up.

js
function sum(numbers) {
  let total = 0;
  for (const n of numbers) {
    total += n;
  }
  return total;
}
const numbers = Array.from({ length: 100000 }, (_, i) => i + 1);
console.log("10万個の合計:", sum(numbers));

Node.js and Chromium both ran without an error and printed the total.

text
10万個の合計: 5000050000
Point

The causes I reproduced in this article are four: no stop condition, a stop condition that is skipped, a setter that assigns to the same property, and too much data making the calls too deep. For the first three, fix the condition or the assignment target. If the data size is the cause, rewrite the code with a loop.

What you get when you catch it with try…catch

This error can be caught with try...catch, just like other errors. I called the first factorial inside try and printed the contents of the error I received.

js
try {
  factorial(5);
} catch (err) {
  console.log("name:", err.name);
  console.log("RangeError か:", err instanceof RangeError);
  console.log("message:", err.message);
}
text
name: RangeError
RangeError か: true
message: Maximum call stack size exceeded

The error type is RangeError, and message contained only Maximum call stack size exceeded. Catching the error only keeps the program from stopping. The cause, where the function never finishes, remains. As shown above, fix the cause, which is the code that keeps calling itself.

​Posted by 86