'Stack' is a data structure that is almost similar to Array but here we can't access data using the index number, we can only add or remove data from the top of the stack. JavaScript uses this data structure to manage execution contexts and control the execution of codes which is called 'Call Stack'.
๐๐ป How does it work?
๐ซด๐ป When we call a function, using the call stack mechanism JavaScript first creates an empty stack and then adds the function serial by as they are called, when their work is done it automatically removes that function from the stack. Let's understand this with an example:
function one(){
console.log(1);
two()
}
function two(){
console.log(2);
three()
}
function three(){
console.log(3);
}
one()
When we run this code, the following things will happen in the following order:
- As soon as we run the code, an empty stack will be created which is shown as anonymous.
- The function
one()
will be invoked and pushed to the stack on anonymous. - Then in function
one()
it will invoke functiontwo()
, - Function
two()
will be added to the stack over functionone()
, - Within function
two()
functionthree()
will be invoked. - Function
three()
will be added to the stack over functiontwo()
. - As there is no function available to call in the function
three()
, after executing the function it will get popped off from the stack. - Now the work of function
two()
is also finished, so it will also get popped off, and then finally functionone()
will be popped off.
In the above procedure call stack works in javascript. We have seen in the example that the function entered at last in the stack got out first from it. So we can say that it follows the LIFO (Last In Fast Out) method. Now let's try to visualize this example with a diagram:
From the above diagram, we can easily visualize how functions are added to the stack, and then after executing they are getting popped off from the top.
With this, I'm concluding my article. If you have any queries or feedback, feel free to comment below or reach me on LinkedIn.
Thank you for reading. Happy learning ๐ค๐ธ