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:
- The function that is called last will execute first
- 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
- JavaScript has only one call stack
- This is why JavaScript is single-threaded
- Each function call creates a new execution context
- After execution, it is removed from the stack
Call Stack + Execution Context
Every time a function is called:
- A new Function Execution Context is created
- It is pushed into the call stack
- 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?
- Function keeps getting added to the stack
- Stack memory gets full
- JavaScript throws an error