Predict the output · Node.js

Microtasks vs Macrotasks

Medium Predict the output Most askedSeen at Meta, Netflix, Vercel, Microsoft

In what order are the letters printed?

What does this print?

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
queueMicrotask(() => console.log("D"));
(async () => {
  console.log("E");
  await null;
  console.log("F");
})();
console.log("G");
  1. A
    B
    C
    D
    E
    F
    G
  2. A
    E
    G
    C
    D
    F
    B
  3. A
    G
    E
    C
    D
    B
    F
  4. A
    E
    G
    B
    C
    D
    F

Check your answer

Loading the editor… (JavaScript is required to run code in your browser.)

Solution

Show the answer

The output is:

A
E
G
C
D
F
B
  1. Synchronous code runs first: A, then the async function body runs synchronously up to its first await (E), then G.
  2. The microtask queue drains next, in the order tasks were queued: the .then callback (C), the queueMicrotask callback (D), then the continuation after await null (F).
  3. Only then does the event loop take the next macrotask — the setTimeout callback (B), even with a 0 ms delay.