Call Stack in JavaScript with examples

 Summary

 in this tutorial, you will learn about the JavaScript Call Stack which is a mechanism to keep track of the function calls.

Introduction to JavaScript Call Stack

JavaScript engine uses a call stack to manage exection context the Global Execution Context and Function Execution Contexts. The call stack works based on the LIFO principle i.e., last-in-first-out.

When you execute a script, the JavaScript engine creates a Global Execution Context and pushes it on top of the call stack.

Whenever a function is called, the JavaScript engine creates a Function Execution Context for the function, pushes it on top of the Call Stack, and starts executing the function.

If a function calls another function, the JavaScript engine creates a new Function Execution Context for the function that is being called and pushes it on top of the call stack.

When the current function completes, the JavaScript engine pops it off the call stack and resumes the execution where it left off in the last code listing.

The script will stop when the call stack is empty.

JavaScript Call Stack Example






When the script runs above code, the JavaScript engine places the global execution context (denoted by main() or global() function on the call stack.










The global execution context enters the creation phase and moves to the execution phase.

The JavaScript engine executes the call to the average(10, 20) function and creates a function execution context for the average() function and pushes it on top of the call stack:










The JavaScript engine starts executing the average() since it is at the top of the call stack.

The average() function calls sum() function. At this point, the JavaScript engine creates another function execution context for the sum() function and places it on the top of the call stack:










JavaScript engine executes the sum() function and pops it off the call stack:










At this point, the average() function is on top of the call stack, JavaScript engine executes it and pops it off the call stack.










Now, the call stack is empty so the script stops executing:










The following picture illustrates the overall status of the Call Stack in all steps:

Summery : -

the key takeaways from the call stack are:

  • It is single threaded. Meaning it can only do one thing at a time.
  • Code execution is synchronous.
  • A function invocation creates a stack frame that occupies a temporary memory.
  • It works as a LIFO ( Last In First Out ) data structure.


Comments

Popular posts from this blog

Every JS developer should know these concepts.. Syntax Parsers, lexical Enviroments and Execution context

SASS vs SCSS in CSS