DEV Community

Ramya Sri M
Ramya Sri M

Posted on

Call Stack in JavaScript

The JS engine uses the call stack to maintain the order of execution for the execution context. It follows Last-In-First-Out (LIFO). This means that the function pushed onto the stack last is the first to come out after completing its execution.

Please go ahead and take a look at my last post, in which I talked about how JS code is executed. Whenever code is executed, a Global Execution Context is created. When the Global Execution Context is created, it is pushed onto the call stack.

Let's look at an example

function add(a,b){
   var ans = a+b;
   console.log(ans);
}
var addition = add(6,5);
Enter fullscreen mode Exit fullscreen mode

call stack
First, the Global Execution Context is pushed onto the call stack. When a function[add()] is invoked, another execution context is created and pushed onto the stack. Once the function is done executing, it returns a value and is popped off the stack. Control then goes back to the Global Execution Context to check if there are any remaining lines of code. If there are none, the Global Execution Context is also popped off the stack, leaving the call stack empty.

If a function calls itself infinitely without an endpoint, a stack overflow occurs.

The call stack is also known by alternative names such as,

  • The execution context stack
  • Program stack
  • Control stack
  • Runtime stack
  • Machine stack.

I hope this explanation helps clarify the concept. If you have any questions or corrections, feel free to ask in the comment section.

Credits to Akshay Saini.

Top comments (0)