Blog |

JavaScript RangeError: Maximum Call Stack Size Exceeded

JavaScript RangeError: Maximum Call Stack Size Exceeded
Table of Contents

The JavaScript RangeError: Maximum call stack size exceeded happens when a function keeps calling itself without any condition to stop, and eventually, the program runs out of space to keep track of these repeated calls.

It's a sign that your program needs a way to stop the function from calling itself endlessly.

This error typically occurs due to:

  • Too many function calls.
  • Issues in handling recursion, e.g. missing base case in a recursive function to stop calling itself infinitely.
  • Out of range operations.

RangeError: Maximum Call Stack Size Exceeded Example

Here’s an example of a JavaScript RangeError: Maximum call stack size exceeded thrown when using a recursive function that does not have a base case:

function myFunc() {
    myFunc();
}

myFunc();

Since the recursive function myFunc() does not have a terminating condition (base case), calling it creates an infinite loop as the function keeps calling itself over and over again until the RangeError: Maximum call stack size exceeded error occurs:

Uncaught RangeError: Maximum call stack size exceeded
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)
    at myFunc (test.js:2:2)

How to Avoid RangeError: Maximum Call Stack Size Exceeded

If this error is encountered when calling recursive functions, make sure that the function has a defined base case to terminate the recursive calls.

In case this error occurs due to an excessive number of function calls or variables, these should be reduced as much as possible. Any out of range operations should also be checked and avoided. These issues can be inspected using the browser console and developer tools.

The earlier example can be updated to include a base case:

function myFunc(i) {
    if (i >= 5) {
        return;
    }
    myFunc(i+1);
}

myFunc(1);

The above code avoids the error since recursive calls terminate when the base case is met.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape