Register Login

What is 'Uncaught RangeError: Maximum Call Stack Size Exceeded' Error?

Updated Jul 24, 2020

The error “Uncaught RangeError: Maximum call stack size exceeded” is common among programmers who work with JavaScript. It happens when the function call exceeds the call stack limit.

Let us look at the error in detail and the solution too.  

What do you Mean by Maximum Call Stack Error?

This error is caused mainly due to the following reasons –

Non-Terminating Recursive Functions

Your browser will allocate a certain amount of memory to all data types of the code you are running. But this memory allocation has a limit. When you call a recursive function, again and again, this limit is exceeded and the error is displayed.

So, call recursive functions carefully so that they terminate after a certain condition is met. This will prevent the maximum call stack to overflow and the error will not pop up.

Problematic Ranges

Some JS programs have ranges of inputs that the user can give. Other programs have functions that may go out of range. When this happens, browsers like Google Chrome will give you the Uncaught RangeError message. But Internet Explorer will crash.

To prevent this, always check the validity of input ranges and how the functions are working with the ranges.

Let us look at an example.

Example

<script>
fun_first();
function fun_first(){
console.log('Hi');
               fun_first();
}
</script>

Uncaught RangeError: Maximum call stack size exceeded

Explanation

In the above example, we are recursively calling fun_first() due to which the error is Uncaught RangeError encountered. The recursive function is called, which then calls another function, and goes on until it exceeds the call stack limit.   

Solution

We should call a recursive function with an If condition. When the code satisfies the condition, the function execution is stopped.

Code Example

<script>
var i=1;
fun_first(i);
function fun_first(i){
               if (i <= 10){
                              console.log('Hi');
                              i=i+1;
                              fun_first(i);
               }
}
</script>

In the above example, we have created an if condition to check the value of i. If the value of i reaches 10, the same function will not be called again.

Conclusion

The Uncaught RangeError is caused when the browser’s hardcoded stack size is exceeded and the memory is exhausted. So, always ensure that the recursive function has a base condition that can stop its execution.   

 


×