WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Intermediate · question 35 of 100

How does the event loop work in JavaScript?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

The event loop is a fundamental part of the JavaScript runtime that manages the execution of code and handles asynchronous operations like network requests and user interactions. It ensures that the application remains responsive and doesn’t block the main thread of the browser or the Node.js environment.

The event loop works by continuously monitoring a queue of tasks and executing them in a specific order. Each task is either a synchronous block of code or an asynchronous operation that will be completed at some point in the future, such as a timer or a network request.

When a synchronous block of code is executed, it runs to completion before any other tasks can be executed. However, when an asynchronous operation is encountered, it is pushed onto a queue of pending tasks and the event loop continues to execute other tasks.

Once the asynchronous operation completes, it is moved to a queue of completed tasks. The event loop checks this queue periodically, and when it finds a completed task, it moves it to the queue of pending tasks, where it can be executed.

Here’s an example of how the event loop works:

    console.log("Task 1");
    
    setTimeout(() => {
        console.log("Task 2");
    }, 0);
    
    console.log("Task 3");

In this example, the console.log() statements are executed synchronously and produce the output "Task 1" and "Task 3". The setTimeout() function is an asynchronous operation that schedules the execution of its callback function ("Task 2") after a specified delay (in this case, 0 milliseconds).

Because the callback function for setTimeout() is an asynchronous operation, it is pushed onto the queue of pending tasks and the event loop continues to execute the synchronous code. Once the delay has elapsed, the callback function is moved to the queue of completed tasks.

When the event loop checks the queue of pending tasks, it finds the completed task ("Task 2") and moves it to the queue of pending tasks, where it is executed. The output of the program is "Task 1", "Task 3", and "Task 2".

Understanding how the event loop works is essential for writing efficient and responsive JavaScript code, especially in modern web applications where asynchronous operations are common.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics