What is the JavaScript event loop and how does it work

· Category: JavaScript

Short answer

The event loop is a mechanism that continuously checks the call stack and task queues, moving callbacks to the stack when it is empty, enabling asynchronous behavior on a single thread.

How it works

  1. Call stack: Tracks function execution. When a function finishes, it pops off the stack.
  2. Web APIs / Node APIs: Handle async operations like timers and network requests off the main thread.
  3. Task queues: Completed callbacks wait in queues. - Macrotask queue: setTimeout, setInterval, I/O. - Microtask queue: Promise callbacks, queueMicrotask, MutationObserver.
  4. Event loop: When the stack is empty, microtasks run first, then one macrotask, then rendering if needed.

Example

console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// Output: A, D, C, B

Why it matters

Understanding the event loop prevents race conditions, helps debug async order, and guides you to use microtasks for urgent work and macrotasks for deferred work.