The error message “Uncaught RangeError: Maximum call stack size exceeded” occurs when a JavaScript function or method calls itself recursively in an infinite loop, causing the call stack to exceed its maximum size. Let’s explore this error further with a couple of examples:
Contents
Example 1 to recreate “Uncaught RangeError: Maximum Call Stack Size Exceeded”: Infinite Recursive Function
function recursiveFunction() { recursiveFunction(); } recursiveFunction();
In this example, the recursiveFunction is called without any condition or base case to terminate the recursion. As a result, the function keeps calling itself indefinitely, leading to the “Uncaught RangeError: Maximum call stack size exceeded” error. The call stack fills up with function calls and eventually exceeds the limit imposed by the JavaScript engine.
Example 2 to recreate “Uncaught RangeError: Maximum Call Stack Size Exceeded: Incorrect Base Case in Recursive Function
function countdown(n) { if (n === 0) { return; } console.log(n); countdown(n - 1); } countdown(5);
In this example, the countdown function is intended to print numbers in descending order until reaching 0. However, a mistake is made by forgetting to include the base case that terminates the recursion. As a result, the function keeps calling itself with a decreasing value of n, but it never reaches the base case to stop the recursion. Eventually, the call stack overflows and the “Maximum call stack size exceeded” error is thrown.
To fix this error, you need to ensure that recursive functions have proper termination conditions or base cases. These conditions should be defined to halt the recursion and prevent an infinite loop. In the second example, adding return before the recursive call when n is 0 would resolve the issue:
function countdown(n) { if (n === 0) { return; } console.log(n); return countdown(n - 1); } countdown(5);
Now, the function will terminate when n reaches 0, preventing an infinite recursion and avoiding the “Maximum call stack size exceeded” error.
It’s important to be cautious when designing recursive functions and ensure that they have proper exit conditions to prevent unintentional infinite loops.
This tutorial really helped to solve ‘Uncaught RangeError: Maximum Call Stack Size Exceeded’ Error in JavaScript