Question presented to candidate: "Walk me through, in exact order, what actually prints if a function has a console.log, then a setTimeout(fn, 0), then a Promise.then(fn), then another console.log — and explain why that order happens."
What a strong answer should cover:
- 📌 Interview term: synchronous code — executes one statement at a time, top to bottom, each statement genuinely blocking the next from starting until it completes.
- 📌 Interview term: asynchronous code — lets long-running or externally-triggered work (a timer, a network request, a file read) happen without blocking the rest of the program; the result is delivered later via a callback, a Promise, or
async/await. - 📌 Interview term: the real, direct answer to the prompt — verified directly: given a synchronous log, a
setTimeout(fn, 0), aPromise.then(fn), and a second synchronous log, the real observed order was all synchronous code first (both logs), then the Promise callback, then thesetTimeoutcallback — never interleaved any other way. - 📌 Interview term: the microtask/macrotask distinction — a precise answer names WHY the Promise callback ran before the
setTimeoutcallback despite both being "asynchronous": Promise callbacks are microtasks, which the event loop always fully drains before running the next macrotask (which is what asetTimeoutcallback is), even asetTimeoutwith a0ms delay. - A precise answer names that "asynchronous" does not mean "runs on a separate thread" — JavaScript itself is single-threaded; asynchronous operations are handled by the surrounding runtime (browser APIs or Node's libuv), which schedules their callbacks back onto the same single JS thread once ready.
Clarifying questions expected:
- None — this is a definitional/comparison question; producing the exact real ordering (not just "sync runs first, async runs later") is the strong signal.
Code / implementation expected: Yes — reproducing the exact real console.log order for the prompt's own scenario is the clearest, most convincing demonstration.