Explain the JavaScript Event Loop
Answer
The event loop is how JavaScript handles asynchronous operations despite being single-threaded.
Components
Execution Order
- Execute synchronous code (call stack)
- Process all microtasks (Promises)
- Process one macrotask (setTimeout, events)
- 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 microtasksetTimeoutis a macrotask