Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer.

Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer.
const out = [];
out.push("A");
setTimeout(() => { out.push("B"); console.log(out.join(" ")); }, 0);
Promise.resolve().then(() => out.push("C"));
out.push("D");
What is printed?
  1. A. A B C D
  2. B. A D B C
  3. C. A D C B
  4. D. A C D B

Correct answer: C. A D C B

Synchronous code runs first (A, D). Promise callbacks are microtasks, run as soon as the current script finishes (C). Timers are macrotasks, run on a later loop turn even with delay 0 (B), which then prints everything.

More Coding Interview Problems questions

Exams that ask this topic