How Does Call Stack Works In Javascript?
Oct 21, 2020
Yesterday I talked about the execution context in javascript. The call stack is basically a collection of multiple execution context
where your code runs.
To learn more about execution context, click here
In simple terms, Call stack
is a stack data structure that stores information to keep track of which code to execute.
Let’s take an example to understand it more clearly.
Steps
- Ignore all functions, until it reaches the
add()
function invocation line. - add() will be pushed to call stack. Execute
add()
- Go through all lines of the
add()
function. Assign variablex: 10
value. - Push
calculate()
on top of the call stack. - Execute all lines of code inside the calculate() function, until reaches its end.
- Return to the line of
calculate()
invocation in the add method. Remove calculate() from the call stack. - Execute all lines of code inside the add() function until reaches its end.
- Return to the line of
add()
invocation. Remove add() from the call stack.
Call Stack is now empty.
Summary
- We start with an empty Call Stack.
- Whenever we invoke a function, it is automatically added to the Call Stack. Once the function has executed all of its code, it is automatically removed from the Call Stack.
- In the end, the call Stack is empty again.
References — Mozilla
Let’s connect on Twitter !