April 2, 2025
JavaScript: Call Stack, Web APIs & the Event Loop
A practical walkthrough of how JS stays single-threaded yet handles async work—call stack, Web APIs, callback queue, the event loop, and microtasks vs macrotasks.
🧠 Introduction
JavaScript is single-threaded, yet it handles asynchronous operations like a pro. Ever wondered how?
Let’s break down the Call Stack, Web APIs, Callback Queue, and Event Loop in a simple way.
📦 Call Stack (Execution Engine)
The call stack is where functions are executed one by one.
function a() {
b();
}
function b() {
console.log("Hello");
}
a();
Stack flow: a → b → console.log
🌐 Web APIs
When async operations happen (like setTimeout, fetch), they are handled outside the JS engine in Web APIs.
⏳ Callback Queue
Once async tasks are completed, their callbacks go into the queue.
🔄 Event Loop (The Brain)
The event loop constantly checks:
- Is the call stack empty?
- If yes → push callback from queue to stack
🔥 Example
console.log("Start");
setTimeout(() => {
console.log("Async");
}, 0);
console.log("End");
Output:
Start
End
Async
Because async callbacks wait for the call stack to be empty.
⚡ Microtasks vs Macrotasks
- Microtasks: Promises
- Macrotasks:
setTimeout
Microtasks run before macrotasks.
🎯 Why This Matters
- Helps debug async bugs
- Improves performance understanding
- Crucial for interviews
🧠 Conclusion
Understanding the event loop separates average developers from great ones. It gives you control over async behavior instead of guessing.
If you want to master JavaScript deeply, start here.