Understanding Call Stack In Javascript

Subscribe to my newsletter and never miss my upcoming articles

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.

function add(x,y){
     const x = 10;
     calculate(x,y);
}

function calculate(x, y){
}

add(5, 10);

Steps

  1. Ignore all functions, until it reaches the add() function invocation line.

  2. add() will be pushed to call stack. Execute add()

  3. Go through all lines of the add() function. Assign variable x: 10 value.

  4. Push calculate()on top of the call stack.

  5. Execute all lines of code inside the calculate() function, until reaches its end.

  6. Return to the line of calculate() invocation in add method. Remove calculate() from the call stack.

  7. Execute all lines of code inside the add() function until reaches its end.

  8. Return to the line of add() invocation. Remove add() from the call stack.

Call Stack is now empty.

js (1).png

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 Stack is empty again.

References - Mozilla


Twitter Follow

Let's connect on Twitter

Comments (1)

Ayodele Samuel Adebayo's photo

Thanks for this...found this educative...knowing what's going on behind the scene is awesome...can you write about "call back" too?..