Call Stack in javascript

Call Stack in javascript

Table of contents

what is call stack ?

Basically call stack is data structure that works on the principle of LIFO(last in first out).

In javascript call stack is used to keeps track of functions invocations(calls).

  • Whenever javascript code starts executing, a global execution context gets created and it is pushed at the bottom of the call stack.
  • When the function get's called, function execution context (FEC) pushed into the call stack. it will get popped out from the call stack when it returns.

let's see with an example:

function firstFunction (){
 secondFunction();
 console.log("This is first function");
}

function secondFunction(){
 thirdFunction();
 console.log("This is second function");
}

function thirdFunction(){
 console.log("This is third function");
}

firstFunction();
// output of above code is :

This is third function

This is second function

This is first function
  • Global execution context created and pushed into the bottom of the call stack

call sta.png

  • firstFunction get's called and the execution context of the firstFunction get pushed into the call stack.

first.png

  • execution of firstFunction get's started, during this secondFunction get's invoked inside firstFunction, due to this execution context of secondFunction get pushed into the call stack.

second.png

  • execution of secondFunction get's started, during this thirdFunction get's invoked inside secondFunction , due to this execution context of thirdFunction get pushed into the call stack.

third.png

  • execution of thirdFunction get's started, code inside thirdFunction get logs into the console, now there is no line of code in thirdFunction, it will get popped from call stack.

  • same will happen to secondFunction and firstFunction functions too, at the end GEC also removed from call stack.