Hello There ๐. In this Blog Post, I'm going to explain something most javascript developers tend to ignore or don't feel like learning. Today we are going to have a look at the javascript call stack ๐
Now... You might be asking yourself why do I need to know this?
Well... To be honest, even I don't like this topic but it's good to know how things work in the background & also understanding this will help you debug your code easily ๐
let's dive in
What is JavaScript CallStack?
In Simple Words, Javascript call stack is a way for the JavaScript interpreter to manage the invocation of multiple functions
- It keeps track of what function is currently running and what function is called from within that function
When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
The call stack adds a function on top of other functions and when it's done with that function it removes it from the stack ( last in, first out )
For example:
We have Two functions below
1 function there() {
2 return hello() + " there";
3 }
4
5 function hello() {
6 return "Hello";
7 }
8
9 there();
- We have Two functions Here
there()
&hello()
. function
there()
returns the return value from the functionhello()
which in our case is the string"Hello"
+ the string" there"
which combined makes itHello there
On line
9
we are invoking the functionthere()
;- The JavaScript engine ignores all other functions till it sees the function invocation. In our Case its
there()
Lets visualize what's happening in the call stack ๐
Here in the chrome debugger, there are many things But, I want you to focus on the call stack section on the right side.
As I go one step forward each time the chrome debugger will show us what's really happening.
Lets begin!
First, we are calling the function
there()
.there()
is added to the call stack.We have a return statement on line
2
. which returns functionhello()
. So before we go all in to complete the return statement we have to go into the functionhello()
.Here we are on line
6
. Because we had thehello()
function on line2
,hello()
is added to the call stack. You can also see it is added on top ofthere()
because that's how the call stack works. they are added on top of each other because its LAST IN FIRST OUT .
Now once it is done with the
hello()
function return statement, the functionhello()
is removed from the stack and it will go back to line2
to finish thethere()
return statement.
Now that it's done with the function
there()
it will be removed from the call stack.
If you learned something from this post please do share it with your friends :D & also thank you so much for reading ๐
Connect with me ๐
Twitter ๐
Discord๐