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.