✅ 1. What is the Call Stack?
The Call Stack is the place where JavaScript executes your code line by line.
- JavaScript is single-threaded
- Only one function can execute at a time
- Functions are added (pushed) to the stack when called
- Removed (popped) when finished
Visual:
| top → console.log() |
| main() |
|_____________________|
If the stack gets too large → Stack Overflow error.
✅ 2. What is the Event Loop?
JavaScript itself is single-threaded,
but the browser (or Node.js) has background threads for async tasks (timers, fetch, DOM events).
The Event Loop:
- Watches the Call Stack
- When stack is empty, it takes tasks from:
- Microtask Queue (promises, mutation observers)
- Macrotask Queue (setTimeout, setInterval, DOM events)
- Pushes them into the Call Stack when it's free
Priority:
Event Loop → Microtasks first → then Macrotasks
🔥 Async Execution Example
Code:
console.log("1");
setTimeout(() => {
console.log("2");
}, 0);
Promise.resolve().then(() => {
console.log("3");
});
console.log("4");
🧠 Step-by-step Execution
Call Stack starts running:
1️⃣ console.log("1")
Output: 1
2️⃣ setTimeout(...)
- The callback is sent to Web APIs (browser timer system)
- After 0ms, it moves to macrotask queue
3️⃣ Promise.then(...)
- Promise callback goes to microtask queue
4️⃣ console.log("4")
Output: 4
🔄 Event Loop Now Runs
First → microtask queue
Output: 3
Then → macrotask queue
Output: 2
📌 Final Output Order
1
4
3
2
🎯 Why This Order?
- Sync code runs first (1, 4)
- Promise (
microtask) runs before setTimeout (macrotask) - Event loop decides the execution order
🧩 Visual Representation
CALL STACK:
runs console.log(1)
runs console.log(4)
empty...
MICROTASK QUEUE:
promise.then → console.log(3)
MACROTASK QUEUE:
setTimeout → console.log(2)
Event loop picks tasks in order:
✔ First microtasks → 3
✔ Then macrotasks → 2
⭐ Short Interview Answer
The Call Stack executes JavaScript synchronously, one function at a time.
The Event Loop handles asynchronous tasks by moving callbacks from the microtask and macrotask queues back into the call stack when it is empty.
Microtasks (Promises) always run before macrotasks (setTimeout).