DeployU
Interviews / Frontend Engineering / What is the event loop and how does it work in JavaScript?

What is the event loop and how does it work in JavaScript?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new feature that needs to make an API call to get some data and then update the UI with the data.

You need to understand how the event loop works so that you can write asynchronous code that is both performant and correct.

The Challenge

Explain what the event loop is in JavaScript and how it works. What is the role of the call stack, the message queue, and the microtask queue?

Wrong Approach

A junior engineer might have a vague understanding of the event loop. They might not be able to explain the difference between the message queue and the microtask queue, or the implications of this difference.

Right Approach

A senior engineer would be able to provide a detailed explanation of the event loop and its different components. They would also be able to explain the difference between the message queue and the microtask queue and would have a clear understanding of how this affects the execution of asynchronous code.

Step 1: Understand the Key Components

ComponentDescription
Call StackA LIFO (Last-In, First-Out) data structure that stores the execution context of the code.
Message QueueA FIFO (First-In, First-Out) data structure that stores the messages to be processed by the event loop.
Microtask QueueA queue for microtasks, such as promise callbacks. Microtasks are executed before the next message in the message queue.
Event LoopA process that constantly checks the call stack and the message queue. If the call stack is empty, it takes the first message from the message queue and pushes it onto the call stack.

Step 2: The Event Loop in Action

Here’s how the event loop works:

  1. When a function is called, it is pushed onto the call stack.
  2. When the function returns, it is popped off the call stack.
  3. When an asynchronous operation is performed, it is offloaded to the browser’s Web API.
  4. When the asynchronous operation is complete, a message is added to the message queue.
  5. The event loop takes the first message from the message queue and pushes its callback function onto the call stack.
  6. The callback function is executed.

Microtasks vs. Macrotasks

The message queue is also known as the macrotask queue. In addition to the macrotask queue, there is also a microtask queue.

  • Macrotasks: setTimeout, setInterval, setImmediate
  • Microtasks: process.nextTick, Promise.then, queueMicrotask

Microtasks are always executed before the next macrotask.

Practice Question

You have a `setTimeout` with a delay of 0ms and a `Promise.then`. Which one will be executed first?