What is stack overflow in Javascript?
You might have heard about something called Stack Overflow. No, I am not talking about the famous platform for developers, but it’s a concept; moreover, it’s a situation. In this article, we will understand the situation, stack overflow in Javascript! But before jumping to it, we need to understand what a call stack is?
What is the call stack?
Through the call stack, the interpreter keeps track of any functions that are called when the script is executed. The way through which the call stacks work is pretty simple. It follows these steps:
- When the script calls a function, it is added to a call stack by the interpreter, after which it resumes executing that function.
- When the function’s execution is finished, the interpreter removes (pops) it from the stack and continues executing the script.
Let’s understand this using a straightforward example.
function welcome(){
hi();
}function hi(){
console.log("Hey there, welcome!");
}welcome();//... More JS code.
The above code will be executed in the format:
- When the interpreter reaches the
welcome()
function invocation, it is added to the call stack. - The
hi()
function invocation is added to the call stack (After thewelcome()
function is added to the call stack, the function is executed. The interpreter also found thehi()
function invocation, hence adding thehi()
function to the call stack too!) - The
hi()
function is executed. - The
hi()
function is removed/popped out of the stack. - The
welcome()
function is executed. - The
welcome()
function is removed/popped from the call stack. - The rest of the javascript code is executed.
An important note: When the script runs, the global execution context function denoted by
main()
orglobal()
is added to the call stack.
Here is a visual representation of the above steps:
What is Stack overflow?
Now, let’s discuss the main concept. The stack overflow situation is built on the call stack, and hence it was essential to understand it.
The call stack has a maximum size assigned. Stack Overflow occurs when the number of function calls added to the stack increases the stack’s maximum limit (the call stack has a maximum size). A classic example to cause such a situation is Recursion. Recursion is a process in which a function calls itself until a terminating condition is found.
An example:
function recursion(){
recursion(); //a function calling itself
}recursion();
The interesting part of the above example is that there is no terminating condition. Hence, the function calls itself infinitely, therefore causing a stack overflow, and thus an error occurs.
If we execute the above code in chrome, we receive this error:
Here we go! This is stack overflow!
If you liked the article, a clap would motivate me on writing more such articles :)