Skip to main content

Explain the JavaScript Event Loop

Answer

The event loop is how JavaScript handles asynchronous operations despite being single-threaded.

Components

Execution Order

  1. Execute synchronous code (call stack)
  2. Process all microtasks (Promises)
  3. Process one macrotask (setTimeout, events)
  4. Repeat

Example

console.log("1");

setTimeout(() => console.log("2"), 0);

Promise.resolve().then(() => console.log("3"));

console.log("4");

// Output: 1, 4, 3, 2

Key Points

  • Microtasks run before macrotasks
  • Promise.then() is a microtask
  • setTimeout is a macrotask