What is the event loop in JavaScript?
Answer
JavaScript is single-threaded — it can only execute one thing at a time. The event loop is the mechanism that enables non-blocking asynchronous behavior. Key components: the Call Stack (where synchronous code executes — LIFO), the Web APIs (browser provides setTimeout, fetch, DOM events — async operations happen here outside the call stack), the Callback Queue/Task Queue (callbacks from Web APIs wait here), and the Microtask Queue (Promise callbacks and queueMicrotask — higher priority than task queue). The event loop continuously checks: if the call stack is empty, it first processes ALL microtasks, then takes ONE task from the callback queue, processes it, then repeats. This explains: console.log("1"); setTimeout(()=>console.log("2"), 0); Promise.resolve().then(()=>console.log("3")); console.log("4") outputs: 1, 4, 3, 2 — synchronous first, then microtasks (Promise), then macrotasks (setTimeout).