Skip to main content

Command Palette

Search for a command to run...

A deep dive into the Event loop in JavaScript

Published
•4 min read•View as Markdown
P

Peter is a Technical writer who has specific interests in software and API documentation. He is also a back-end developer who loves to share his knowledge of programming concepts on his blog and for other publications.

In the world of JavaScript, the event loop is often misunderstood and challenging for many developers, both junior and senior. Many developers struggle to understand how the event loop enables JavaScript to execute programs asynchronously. In this article, I will explain the details of the event loop and its role in the JavaScript runtime.

Synchronous programming

JavaScript is a single-threaded language, meaning it executes instructions one at a time. Like most languages, JavaScript waits for a program to finish executing before moving to the next one. For example, let's take a look at the following code:

console.log("I") 
console.log("Love") 
console.log("Ice Cream")

// Output: 
// I 
// Love 
// Ice Cream

The program runs synchronously, from top to bottom. The first function is called and logged, then the program runs the next function, followed by the third function. You can see they are executed one after the other. Now, let's look at the following code:

console.log("Start")

setTimeout(() => { 
console.log("Timer"),
 2000})

console.log("End")

// Output: 

// "Start" 
// "End" 
// "Timer"

Notice the result of the above code. The first function is executed and logs its result to the console, and the last function gets logged to the console, and then after two seconds, the middle function gets logged to the console. You might be wondering why was "Timer" not logged immediately the first function. When the program gets to the setTimeout() function it waits for two seconds before its gets executed, but the program doesn't wait for the timer to finish, instead it moves to the next line of code. And when the timer is up, the callback function with be called and executed. This what makes JavaScript non-blocking. And what makes JavaScript executes asynchronous code with a single thread is the event loop.

Before we understand what an event loop is, lets look at some of these concepts:

Call stack: also known as an execution stack is a one of the components of the JavaScript engine that executes JavaScript code. The call stack follow a Last In First Out(LIFO) method; think of it as a stack of plates. The last one that is added to the stack will be the first that gets removed.

Web APIs: These are browser APIs that allows JavaScript to interact with the browser. They are interfaces that give JavaScript access to interact with the browser. For example, setTimeout, fetch(), Document object model(DOM), etc. They are not part of the JavaScript code; they are executed on the browser.

Callback queue: This is where callback functions wait before they are passed to the call stack and executed.

Event Loop

The event loop is mechanism in the JavaScript runtime that is responsible for managing the call stack and the callback queue. Here is a graphical representation of the event loop works:

Now, let's see how JavaScript executes asynchronous operations under the hood. In the previous example, the first function is sent to the top of the call stack, also known as the execution stack. After it gets executed and logs its result, it is removed from the call stack. Then the program moves to the next line of code and calls the setTimeout function, passing it to the call stack. The call stack then passes the setTimeout function to the Web APIs because setTimeout is not part of the JavaScript code and only the Web APIs understand it. The setTimeout starts counting in the background while the program moves to the next line of code and sends the next function to the call stack. It gets executed and is logged to the console. Then it gets removed from the call stack. After the timer has stopped in the Web APIs, the callback function is passed to the callback queue. The event loop then checks if the call stack is empty. If the call stack is empty, the event loop moves the callback function from the callback queue to the call stack, and then it gets executed and logs its result.

Conclusion

The event loop is what makes asynchronous programming possible in JavaScript. In spite of JavaScript's single-threaded nature, asynchronous operations such as database operations, fetching a resource from an API, fetching files, etc., can be managed effectively. This makes JavaScript applications responsive and efficient. The event loop makes JavaScript non-blocking, meaning that it doesn't wait for an asynchronous operation to complete before moving to the next line of code.

So, I hope you now have a good understanding of how the event loop works in JavaScript. Your understanding of the event loop will help you write efficient and responsive applications.