How Does Call Stack Works In Javascript?

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.

  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 !

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store