What is the Call Stack?
A call stack is a mechanism to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function.
Before learning Call-stacks workflow, let's go through some common terminologies that are used here to understand things better.
Top: It means the Top most element that is currently being executed.
Push: When we add a function to the top of the call stack, the process is called Push.
Pop: After executing the process where the functions are removed from the call stack is known as Pop.
How does the Call Stack Work?
Call Stack basically works on the LIFO(Last In, First Out ) principle. That means the function that enters the stack at last finishes at first, and then the remaining functions finish.
Let's understand this with diagrams and examples,
console.log("first Function completed");
console.log("second Function completed");
// first Function completed
// second Function completed
So From the output, you can understand that
firstFunction() is executed before then
secondFunction() completes its execution. As mentioned before it's because of the LIFO principle.
Now Let's understand how it's working behind the scenes with some diagrams.
At first Global object/Window object is created in the Call stack
secondFunction() is called, it creates an empty stack frame & its execution context. And the stack is pushed to the Top of the Call-stack.
secondFunction() starts executing, it calls another function
firstFunction() . Just like the previous one, it creates another empty stack and pushes it to the Top of the call stack.
At this point, all of the required functions are pushed to the Class Stack in a particular sequence, where the
firstFunction() function is at the top of the Class Stack
firstFunction() executes and Pops it out from the call stack.
After the removal of the
secondFunction() is the Top function. And just like the previous function it executes and pops out from the stack.
As soon as the execution of
What is Stack-Overflow?
Wait wait; we are not discussing about the popular website where you can ask your questions and get answers!
We are discussing the concept of Stackoverflow.
Let's understand this concept,
The call stack has a maximum size of memory allotted. 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).
One example is Recursion without a base case,
Here We haven't added the base case, So it's an infinite recursive call. The
Recursion() will run until the browser throws a “Maximum call size exceeded”. And that is a stack overflow.
To sponsor my work, please visit: Arindam's Sponsor Page and explore the various sponsorship options.
Thank you for Reading :)