5 min read
ā¢Question 3 of 50hardWhat is the Event Loop in JavaScript?
Understanding asynchronous JavaScript and the event loop.
What You'll Learn
- How the event loop works
- Microtasks vs macrotasks
- Execution order
What is the Event Loop?
The event loop allows JavaScript to perform non-blocking operations despite being single-threaded.
How It Works
- Execute synchronous code in the call stack
- Check microtask queue (Promises)
- Check macrotask queue (setTimeout, setInterval)
- Repeat
Example
code.jsJavaScript
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// Output: 1, 4, 3, 2Why This Order?
- 1, 4: Synchronous code runs first
- 3: Microtasks (Promises) run next
- 2: Macrotasks (setTimeout) run last