How JavaScript Works: Execution Context & The Event Loop
JavaScript is famously described as a single-threaded, non-blocking, asynchronous, concurrent runtime.
At first glance, this sounds like a contradiction:
- If JavaScript is single-threaded, it has only one Call Stack and can do only one thing at a time.
- If it can only do one thing at a time, why doesn't your web page freeze whenever you fetch data from a server or set a timer?
The answer lies in the JavaScript Runtime Architecture and its central conductor: The Event Loop.
1. The Core Architecture: Engine vs. Runtime
When you run JavaScript in a browser (like Chrome or Brave) or on a server (like Node.js), JavaScript code does not live in isolation.
┌─────────────────────────────────────────────────────────────┐
│ JavaScript Runtime │
│ │
│ ┌─────────────────────────┐ ┌───────────────────────┐ │
│ │ JS Engine (V8) │ │ Web APIs / Node │ │
│ │ ┌─────────┐ ┌─────────┐ │ │ ┌───────────────────┐ │ │
│ │ │ Memory │ │ Call │ │ │ │ DOM / fetch() / │ │ │
│ │ │ Heap │ │ Stack │ │ │ │ setTimeout() │ │ │
│ │ └─────────┘ └─────────┘ │ │ └───────────────────┘ │ │
│ └─────────────────────────┘ └───────────┬───────────┘ │
│ │ │
│ ┌──────────────────────────────┘ │
│ ▼ │
│ ┌─────────────────────────┐ ┌───────────────────────┐ │
│ │ Microtask Queue │ │ Macrotask Queue │ │
│ │ (Promises / VIP queue) │ │ (Timers / Events) │ │
│ └────────────┬────────────┘ └───────────┬───────────┘ │
│ │ │ │
│ └──────────────┬───────────────┘ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ EVENT LOOP │ │
│ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
1. Memory Heap
Where memory allocation happens. Objects, variables, and arrays you declare are allocated here in memory.
2. Call Stack (LIFO: Last In, First Out)
The execution stack. Every time a function is invoked, an Execution Context is pushed onto the stack. When the function returns, its frame is popped off. Because JavaScript has only one Call Stack, it can only execute one line of code at any given microsecond.
3. Web APIs / C++ Background Threads
Features provided by the host environment (Browser or Node.js), not the JS engine itself:
setTimeout()andsetInterval()fetch()andXMLHttpRequest- DOM events (
addEventListener)
When you call setTimeout, the JS engine offloads the timer countdown to the host environment's background threads, keeping the Call Stack unblocked!
2. Interactive Event Loop & Call Stack Stepper
Step through classic asynchronous execution orders in real-time. Watch how the engine moves tasks between the Call Stack, Web APIs, Microtask Queue, and Macrotask Queue.
Event Loop & Asynchronous Runtime Stepper
V8 ArchitectureWatch the Call Stack, Web APIs, Microtask (VIP) Queue, and Macrotask Queue interact step-by-step.
Initial state: Script is loaded. Call stack, queues, and console are clean.
console.log("1");
setTimeout(() => {
console.log("2");
}, 0);
Promise.resolve().then(() => {
console.log("3");
});
console.log("4");- Execute synchronous code in the Call Stack until it is completely empty.
- Drain all pending callbacks in the Microtask Queue (Promises,
queueMicrotask) before touching anything else. - Pick one task from the Macrotask Queue (
setTimeout, I/O) and push it to the Call Stack. Repeat!
3. Microtasks vs. Macrotasks: The Priority Duel
Not all asynchronous callbacks are treated equally. The runtime splits callbacks into two queues with strict priority rules:
1. The Microtask Queue (VIP Priority)
- Sources: Promises (
.then(),.catch(),.finally()),async/awaitresumptions, andqueueMicrotask(). - Behavior: The Event Loop will completely drain the Microtask Queue before touching any Macrotask. If microtasks enqueue more microtasks, they will all execute before the browser paints or runs any timer!
2. The Macrotask Queue (Task Queue)
- Sources:
setTimeout(),setInterval(),setImmediate()(Node.js), and I/O callbacks. - Behavior: The Event Loop processes only one macrotask per tick, then immediately checks if new microtasks appeared.
4. The Famous Interview Puzzle: Can You Predict the Output?
console.log("1");setTimeout(() => { console.log("2");}, 0);Promise.resolve().then(() => { console.log("3");});console.log("4");Step-by-Step Breakdown:
console.log("1")runs synchronously Prints1.setTimeout(..., 0)registers a timer in Web APIs. The 0ms timer expires immediately and placesconsole.log("2")in the Macrotask Queue.Promise.resolve().then(...)creates a resolved promise and enqueuesconsole.log("3")in the Microtask Queue.console.log("4")runs synchronously Prints4.- The Call Stack is now empty! The Event Loop checks the Microtask Queue first Prints
3. - Microtask queue is empty. The Event Loop takes the first item from the Macrotask Queue Prints
2.
Final Output:
1
4
3
2
[!IMPORTANT] Why
setTimeout(..., 0)is not instantaneous: Setting a timeout delay to0does not mean "execute immediately". It means "register a timer that expires in 0ms, and place its callback in the Task Queue". The callback will only run after all synchronous code and all pending microtasks have finished!
5. Flashcards & Core Concepts
Why is JavaScript called 'single-threaded'?
Which has higher priority: the Microtask Queue or the Macrotask Queue?