Call Stack in JavaScript

Call Stack in JavaScript

Stack em up...

In this article we explore how function calling actually works with the help of call-stack, how functions get pushed and popped basis of their position in the stack and how this helps in execution of a JS program !!! 🙋


🔱 What is the Call Stack in JS ?

  • Call stack is used by JavaScript to keep track of multiple function calls.
  • It is basically like the popular data structure 'stack' where data can be pushed and popped and follows the Last In First Out (LIFO) principle.
  • When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
  • Any functions that are called by that function are added to the call stack further up, and run where their calls are reached.
  • When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing.
  • If the stack takes up more space than it had assigned to it, it results in a "stack overflow" error.

🈹 How Call Stack works in JS ?

Let us look at the below example to see how the call stack works :

function greet1() {
  console.log("Namaste");
}

function greet2() {
  greet1();
  console.log("Chai Pee Lo!");
}

greet2();

Step 1 :

When the code loads in memory, the global execution context gets pushed in the stack.

1.png

Step 2 :

The greet2() function gets called, and the execution context of greet2() gets pushed into the stack.

1.png

Step 3 :

The execution of greet2() starts and during its execution, the greet1() function gets called inside the greet2() function. This causes the execution context of greet1() to get pushed in the call stack.

1.png

Step 4:

Now the greet1() function starts executing. A new stack frame of the console.log() method will be pushed to the stack.

1.png

Step 5:

When the console.log() method runs, it will print “Namaste” and then it will be popped from the stack. The execution context go will back to the function and now there not any line of code that remains in the greet1() function, as a result, it will also be popped from the call stack.

Step 6:

This will similarly happen with the console.log() method that prints the line “Chai Pee Lo!” and then finally the function greet2() would finish and would be pushed off the stack.


In summary, then, 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. Ultimately, the Stack is empty again.

✔️✔️✔️Keep Stacking Skills✔️✔️✔️