Async & Promisesmedium

Explain the Event Loop — what is the output order?

Explain the JavaScript event loop, call stack, microtask queue, and macrotask queue. What order does the following code execute?

Asked at Amazon, Uber, Google, Tenable

#event loop#microtasks#macrotasks#promises

Answer

// Usage
// Use this pattern to reason about callback ordering in bug reports.
console.log('1')               // sync — runs first

setTimeout(() => {
  console.log('2')             // macrotask — runs last
}, 0)

Promise.resolve().then(() => {
  console.log('3')             // microtask — runs before macrotask
})

console.log('4')               // sync — runs second

// Output: 1, 4, 3, 2

// ─────────────────────────────────────────────────────────
// How it works:
// 1. Synchronous code runs on the call stack first.
// 2. After the stack clears, ALL microtasks run (Promise
//    .then, queueMicrotask, MutationObserver).
// 3. Then ONE macrotask runs (setTimeout, setInterval,
//    I/O, UI rendering).
// 4. After that macrotask, microtasks flush again.
// 5. Repeat.

// Key: microtasks always drain before the next macrotask.

Practise more Async & Promises questions →