Maximum call stack size exceeded error
When you run the above script you can see the call stack grows until it hits a maximum limit: the browser hardcoded stack size or memory exhaustion . So, whenever you are trying to code a recursive function then you'll need a base case that stops the function to invoke itself .
How to fix Maximum call stack size exceeded error
Be considerate while calling functions , also dry run is the best practice to prevent them. It's possible to cause infinite recursion in a fully promisified code, too. That can happen if the promises in a chain don't actually perform any asynchronous execution , in which case control never really returns to the event loop, even though the code otherwise appears to be asynchronous. That's when it's useful to wrap your recursive function call into a -
- setImmediate or
Also, you can localize the issue by setting a breakpoint on RangeError type of exception , and then adjust the code appropriately. Moreover, you can managed to find the point that was causing the error by check the error details in the Chrome dev toolbar console , this will give you the functions in the call stack, and guide you towards the recursion that's causing the error.
Memory limit of Call Stack
The Call Stack is what a program uses to keep track of method calls. The call stack is made up of stack frames — one for each method call. It is primarily used for function invocation (call). Since the call stack is single, function(s) execution, is done, one at a time, from top to bottom . It means that the call stack is synchronous .
When you enter a function, an entry for that function is pushed onto the Call stack and when you exit from the function, that same entry is popped from the Call Stack. Each method call creates its own stack frame , taking up space on the call stack. That's important because it can impact the space complexity of an algorithm, especially when we use recursion. if you provide too many arguments or caught inside any unhandled recursive call. You will encounter Maximum call stack size exceeded error. For example:
All functions arguments must fit on callstack(at least pointers of each argument). Here Array.apply(null, new Array(1000000)) , the currentLocalVariables object will be huge because it will have 1000000 variables inside. Since .apply() will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw Maximum call stack size exceeded error.