<vetted />
JavaScript
Mid-Level
Question 6 of 10

How does JavaScript handle running multiple things at once?

Quick Answer

The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations and using a callback queue.

Detailed Answer5 paragraphs

JavaScript is single-threaded, but the event loop allows it to perform non-blocking asynchronous operations. Understanding the event loop is crucial for writing performant JavaScript.

The runtime consists of: the Call Stack (where function execution contexts are pushed/popped), the Web APIs (browser-provided APIs like setTimeout, fetch, DOM events), the Callback Queue (also called Task Queue, where callbacks wait), and the Microtask Queue (for Promises, queueMicrotask, MutationObserver).

When async operations complete, their callbacks are placed in the appropriate queue. The event loop's job is to look at the call stack and the queues: if the call stack is empty, it takes the first item from the microtask queue and pushes it to the call stack. Only when the microtask queue is empty does it take from the callback queue.

Microtasks have priority over regular tasks. This means Promise callbacks execute before setTimeout callbacks, even if the setTimeout was set to 0ms. This is why: Promise.resolve().then(() => console.log('promise')) and setTimeout(() => console.log('timeout'), 0) will always log 'promise' first.

Understanding this helps avoid common pitfalls like blocking the main thread, creating race conditions, and debugging timing issues in async code.

Key Takeaway

The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations and using a callback queue.

Ace your interview

Ready to Land Your Dream Job?

Join our network of elite AI-native engineers.