Find a subject or note

13 results found

JavaScriptArray Methods, Loop Mechanics & The Async Trap

Mastering slice vs splice, search & reduce patterns, loop intent (for...in vs for...of vs map), and the async forEach trap.

JavaScriptasync / await & Modern Asynchronous Flow

Mastering async functions, the non-blocking await keyword, error handling with try/catch, and avoiding performance waterfalls.

JavaScriptcall(), apply(), bind() (Controlling this)

How to explicitly control function execution context in JavaScript using call, apply, and bind.

JavaScriptErrors, try/catch & Defensive Design

Understanding built-in error types, the Error object, custom error classes, async handling, and defensive validation patterns.

JavaScriptThe Event Loop

How JavaScript coordinates synchronous code, the Call Stack, Microtask Queue, and Macrotask Queue.

JavaScriptFetch API, HTTP & Web APIs

HTTP fundamentals, URLSearchParams, response handling, CORS, AbortController, and production service layers.

JavaScriptFirst-Class Functions, Callbacks & Closures

How first-class functions, callbacks, and closures connect to form the foundation of modern JavaScript.

JavaScriptObject Utilities (keys, values, entries, fromEntries)

How Object.keys, Object.values, Object.entries, and Object.fromEntries bridge objects and arrays in JavaScript.

JavaScriptPromises & Promise Combinators

Understanding asynchronous execution, Promise lifecycles, error propagation, and Promise combinators (all, allSettled, race, any).

JavaScriptReturn, Scope & Hoisting in Functions

How return statements, lexical scope, and hoisting determine how functions execute in JavaScript.

JavaScriptSecurity Basics: XSS & Safe DOM Rendering

Cross-Site Scripting (XSS) mechanics, safe DOM manipulation, innerHTML vs textContent, and the validation vs sanitization pipeline.

JavaScriptShallow vs. Deep Copy (Spread Pitfalls & JSON Limits)

Understanding object references, shallow copy pitfalls with spread, JSON limitations, and structuredClone.

JavaScriptWeb Storage: localStorage, sessionStorage & Cookies

Client-side storage mechanisms in JavaScript: comparing localStorage, sessionStorage, and Cookies for interview prep.

The Event Loop

JavaScript is single-threaded: it has only one Call Stack and executes one piece of code at a time. Yet web applications routinely handle network requests, timers, DOM user events, and smooth animations without freezing the interface.

How does this work? Through the Event Loop—the runtime coordinator that continuously monitors the Call Stack and orchestrates work from two asynchronous queues: the Microtask Queue and the Macrotask Queue.

JavaScript Event Loop Architecture diagram showing Call Stack, Microtask Queue, Macrotask Queue, and Browser Rendering opportunity.
The Event Loop cycle: Empty the Call Stack → Drain ALL Microtasks → Browser Render Opportunity → Execute 1 Macrotask → Repeat.

The Three Core Pillars

To master any Event Loop interview question, you only need to understand three components and how they interact:

1. The Call Stack

The Call Stack is a standard LIFO (Last In, First Out) data structure. Every time your code invokes a function, a new execution frame is pushed onto the stack. When the function returns, its frame is popped.

  • Synchronous execution: Your synchronous JavaScript code executes from top to bottom right here.
  • Run-to-completion: JavaScript never interrupts an active call frame. While synchronous code is executing on the Call Stack, nothing else can run—no timers, no network callbacks, and no DOM rendering.

2. The Microtask Queue

The Microtask Queue is a FIFO (First In, First Out) queue dedicated to high-priority asynchronous callbacks.

Common sources of microtasks include:

  • Promise.then(), Promise.catch(), and Promise.finally()
  • queueMicrotask(callback)
  • Resuming after an await statement inside async functions
  • MutationObserver DOM mutation callbacks

The Critical Microtask Rule: Once the Call Stack becomes completely empty, the Event Loop turns immediately to the Microtask Queue. ALL microtasks must finish before anything else happens. If a microtask itself schedules another microtask, that new microtask is pushed to the back of the queue and executed in the same cycle before any macrotask can run.

3. The Macrotask Queue (Task Queue)

The Macrotask Queue (often referred to simply as the Task Queue) is also a FIFO (First In, First Out) data structure for standard asynchronous tasks.

Common sources of macrotasks include:

  • setTimeout() and setInterval() callbacks
  • DOM events (user clicks, inputs, scrolls)
  • Network I/O callbacks (fetch response handlers in Node)
  • setImmediate() (Node.js runtime)

The Critical Macrotask Rule: Unlike the Microtask Queue where every task must clear out, the Event Loop executes ONE macrotask at a time. Once that single macrotask finishes running, the Event Loop checks the Microtask Queue again, allows the browser to render any visual changes, and only then proceeds to the next macrotask.

Call Stack vs. Microtask Queue vs. Macrotask Queue at a Glance

Component

Data Structure

Typical APIs & Sources

Execution Rule per Turn

Impact on Browser Rendering

Call Stack

LIFO (Stack)

Synchronous code, initial script, function calls

Runs to completion immediately from top to bottom

Blocks rendering completely while active

Microtask Queue

FIFO (Queue)

Promise.then, queueMicrotask, await resumes

Drains ALL tasks in queue until 100% empty

Executes right before render; infinite loop freezes UI

Macrotask Queue

FIFO (Queue)

setTimeout, setInterval, DOM clicks, I/O

Executes EXACTLY ONE task per loop turn

Yields to browser rendering between each task

Tracing Execution Order

Interviewers love presenting short code snippets mixing synchronous logs, setTimeout, and Promise resolutions to test whether you understand the exact execution order.

Study this classic example:

event-loop-challenge.js
console.log('1: Synchronous Start');

setTimeout(() => {
  console.log('2: Macrotask (setTimeout)');
}, 0);

Promise.resolve().then(() => {
  console.log('3: Microtask (Promise 1)');
}).then(() => {
  console.log('4: Microtask (Promise 2)');
});

queueMicrotask(() => {
  console.log('5: Microtask (queueMicrotask)');
});

console.log('6: Synchronous End');
Notice how setTimeout delay is 0ms, but Promises and queueMicrotask execute first.
Think it throughWhat is the exact console output order and why?

The console outputs in this exact order:

1: Synchronous Start
6: Synchronous End
3: Microtask (Promise 1)
5: Microtask (queueMicrotask)
4: Microtask (Promise 2)
2: Macrotask (setTimeout)

Step-by-step breakdown:

  1. Synchronous code on Call Stack:
    • console.log('1: Synchronous Start') runs immediately.
    • setTimeout(..., 0) registers a timer with the browser Web API. Its callback is scheduled in the Macrotask Queue.
    • Promise.resolve().then(...) schedules the callback in the Microtask Queue.
    • queueMicrotask(...) schedules its callback in the Microtask Queue.
    • console.log('6: Synchronous End') runs immediately.
  2. Call Stack is now empty! The Event Loop checks the Microtask Queue:
    • Runs 3: Microtask (Promise 1). That .then() returns a resolved promise, which enqueues 4: Microtask (Promise 2).
    • Runs 5: Microtask (queueMicrotask) (already in FIFO queue).
    • Runs 4: Microtask (Promise 2) (enqueued during the microtask turn).
  3. Microtask Queue is now empty! Browser has an opportunity to paint.
  4. Event Loop takes ONE macrotask:
    • Pops 2: Macrotask (setTimeout) into the Call Stack and logs it.

Browser Rendering & Microtask Starvation

Why does the distinction between "all microtasks" and "one macrotask" matter in production systems?

Because the browser repaints the screen between macrotasks, after all microtasks have resolved:

  • Healthy Macrotask Loops: If you break long-running tasks using recursive setTimeout(processChunk, 0), the browser has a window between each chunk to handle user input, update layout, and render at 60fps.
  • The Microtask Starvation Trap: If a microtask continuously schedules another microtask (e.g. recursive queueMicrotask or unconstrained chained promises), the Microtask Queue never empties. The Event Loop will never move on to Macrotasks and the browser will never render, completely freezing the tab!

Quick Memory Checklist

Keep these rapid-fire bullet points in mind during your interview prep:

  • Call Stack: LIFO. Synchronous execution. While busy, blocks everything.
  • Event Loop check: Only triggers when Call Stack is completely clear.
  • Microtask Queue: FIFO. Drains all items before any macrotask can run.
  • Macrotask Queue: FIFO. Runs one item per turn, giving the browser a rendering window.
  • Starvation risk: Infinite microtasks starve macrotasks and prevent browser repainting.
  • Mnemonic: S - M - R - M: Synchronous (Stack) → Microtask flush → Render window → Macrotask single.