TechnicalMedium JavaScript
Explain the JavaScript event loop, including microtasks and macrotasks.
Asked for Frontend Developer, Full-Stack Developer, Mobile Developer
Why they ask this: Shows whether you understand how async code actually runs, which matters for debugging ordering and UI freezes.
Answer
JavaScript runs your code on one thread with a call stack. Async work (timers, network, DOM events) is handled by the browser or Node.js, and their callbacks are queued.
The event loop repeats:
- Run the current script until the call stack is empty.
- Run all microtasks: promise callbacks (
.then,awaitcontinuations) andqueueMicrotask. - Let the browser render if needed.
- Take one macrotask (task) such as a
setTimeoutcallback or an event handler, run it, and go back to step 2.
js
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// Output: 1, 4, 3, 2Microtasks always run before the next timer, even a 0 ms one. A long synchronous loop blocks everything, including clicks and rendering.
Can you explain this in your own words?