Home Courses Call Stack Explained Simply

Call Stack Explained Simply

Call Stack is a mechanism in JavaScript that keeps track of function execution.

In simple terms:

It manages the order in which functions are called and executed.


Key Concept: LIFO Principle

Call stack follows the LIFO (Last In, First Out) principle.

This means:

  1. The function that is called last will execute first
  2. The function that is called first will finish last


How Call Stack Works

Let’s understand step-by-step with an example:


function first() {
second();
}

function second() {
third();
}

function third() {
console.log("Hello");
}

first();


Execution Flow

Step 1:

Global Execution Context is pushed into the stack

[ Global ]

Step 2:

first() is called → added to stack

[ Global, first ]

Step 3:

Inside first(), second() is called

[ Global, first, second ]

Step 4:

Inside second(), third() is called

[ Global, first, second, third ]

Step 5:

console.log() runs and finishes → removed from stack

[ Global, first, second, third ]
→ third finishes → removed

Step 6:

Functions start returning (LIFO)

[ Global, first, second ]
→ second finishes

[ Global, first ]
→ first finishes

[ Global ]
→ program ends


Important Points

  1. JavaScript has only one call stack
  2. This is why JavaScript is single-threaded
  3. Each function call creates a new execution context
  4. After execution, it is removed from the stack


Call Stack + Execution Context

Every time a function is called:

  1. A new Function Execution Context is created
  2. It is pushed into the call stack
  3. After execution, it is popped out


Stack Overflow (Important Interview Concept)

If a function keeps calling itself without stopping, it creates an infinite loop in the call stack.

Example:


function test() {
test();
}

test();

Output:

RangeError: Maximum call stack size exceeded


Why This Happens?

  1. Function keeps getting added to the stack
  2. Stack memory gets full
  3. JavaScript throws an error


Share this lesson: