What is Call Stack in JavaScript

call-stack-in-javascript

JavaScript Call Stack is a mechanism to keep track of multiple function calls or we can say call stack is to manage execution contexts.  The call stack is where the whole javascript code is getting executed.

When a function invokes execution, the JavaScript engine creates a function execution context for that function and gets pushed into the call stack. And when return from the function, the specified execution context gets popped out from the call stack. It follows the Last In First Out (LIFO) principle.

Let's see how the below code is executed in the call stack.

function a(){
	console.log("inside function a");
}

function b(){
	a();
}

b();

1. When the script begins, the JavaScript engine creates a global execution context (global() function) and pushed it into the call stack.

global execution context

2.  When JS invokes function b(), it creates an execution content to b() and is placed on top of global execution content.

functional execution diagram

3. Then begin to execute b(), because it was at the top of the call stack. And when function a() was invoked from function b(), another execution context for a() was created and placed on top of b().

functional execution diagram

 

4. Here global() is the global execution context, a() and b() are functional execution context. 
After the execution of function a(), the execution context for a() was popped out from the call stack.

popped out diagram

5. Then execution context for function b() gets popped out. Finally, the call stack gets empty the script stops execution.

When the call stack was filled with many execution contexts(like infinite recursive function calls), It results in Uncaught RangeError: Maximum call stack size exceeded.