How Does Call Stack Works In Javascript?

Deepak Kumar
Oct 21, 2020

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.

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 the 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.

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

ReferencesMozilla

Let’s connect on Twitter !

--

--

Deepak Kumar

sharing insights on AI, software development, designing scalable system