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:

  1. Run the current script until the call stack is empty.
  2. Run all microtasks: promise callbacks (.then, await continuations) and queueMicrotask.
  3. Let the browser render if needed.
  4. Take one macrotask (task) such as a setTimeout callback 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, 2

Microtasks 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?

Back to question bank