The Event Loop is JavaScript's mechanism for handling asynchronous operations. It continuously checks the call stack and task queues, executing callbacks from the microtask queue (Promises) before the macrotask queue (setTimeout, events).
JavaScript is single-threaded but handles async operations through the Event Loop.
Key Components:
Call Stack: Executes synchronous code, one frame at a time
Web APIs / Node APIs: Handle async operations (timers, fetch, I/O)
Task Queue (Macrotasks):
Microtask Queue:
Execution Order:
console.log('1: Start');
setTimeout(() => {
console.log('2: setTimeout');
}, 0);
Promise.resolve()
.then(() => console.log('3: Promise 1'))
.then(() => console.log('4: Promise 2'));
console.log('5: End');
// Output order:
// 1: Start
// 5: End
// 3: Promise 1
// 4: Promise 2
// 2: setTimeout
// Explanation:
// - Sync code runs first (1, 5)
// - Microtasks (Promises) run before macrotasks
// - setTimeout is a macrotask, runs last