What is the Event Loop?
The event loop is what allows JavaScript to handle asynchronous operations despite being single-threaded. It's the mechanism that coordinates the call stack, task queue, and microtask queue.
💡 Key insight
JavaScript is single-threaded but non-blocking. The event loop manages this by processing tasks from the task queue when the call stack is empty.
Key Components
- Call Stack: Where synchronous code executes (LIFO)
- Task Queue: Where asynchronous callbacks wait (FIFO)
- Microtask Queue: Where promises and mutation observers wait (higher priority)
- Event Loop: Continuously checks if the call stack is empty and moves tasks from queues
Execution Order
- Synchronous code executes immediately
- Microtasks (Promises) execute before tasks
- Tasks (setTimeout, events) execute
- Browser rendering happens between tasks
Common Mistakes
- Blocking the event loop with long synchronous operations
- Assuming setTimeout with 0ms runs immediately
- Forgetting that promises are microtasks (higher priority)
- Using recursive functions that cause stack overflow
Quick Quiz
1. What is the event loop?
2. Which has higher priority: microtasks or macrotasks?
3. What happens when the call stack is empty?
4. Which is a macrotask?
Summary
- Event loop coordinates async operations in single-threaded JS
- Call stack handles synchronous code
- Task queue holds macrotasks (setTimeout, events)
- Microtask queue holds promises (higher priority)
- Microtasks execute before macrotasks
- Avoid blocking the event loop with heavy operations
