π What is Call Stack in JavaScript? (Explained Simply)
The Call Stack is where JavaScript executes your code.
It is a data structure that follows one simple rule:
π Last In, First Out (LIFO)
The last function added to the stack runs first.
π§ How Call Stack Works
When a function is called:
- It gets pushed into the Call Stack.
- JavaScript executes it.
- After completion, it gets removed (popped).
JavaScript can only execute one thing at a time,
so it uses the Call Stack to manage everything.
π» Example
function first() {
console.log("First");
}
function second() {
first();
console.log("Second");
}
second();
π What Happens Internally?
-
second()is pushed into stack. - Inside it,
first()is pushed. -
first()runs and is removed. - Then
second()continues.
π½ Simple Real-Life Example
Imagine a stack of books.
You always place a book on top.
You always remove the top book first.
Thatβs exactly how Call Stack behaves.
π― Important Interview Point
The Call Stack works on:
Last In, First Out (LIFO)
Understanding this helps you understand:
- Event Loop
- setTimeout behavior
- Stack overflow errors
Top comments (0)