JavaScript Event Loop in a Nutshell

Check out all my other posts in My Technical Articles

Yu-Ming, CHANG (he/him)
2 min readApr 24, 2022

Before you continue reading, I assume you already know the concept of call stack, Web API and callback queue. If you haven’t, check out the event loop on MDN first. It will give a conceptual idea of what it is.

What is JavaScript?

JavaScript is a single-threaded synchronous and blocking language by itself.

Yes, it is a synchronous language, meaning the codes are executed line by line and it will only move on to the next line after it finishes all current instructions.

Yes, it is blocking, meaning user cannot interact with browser before all codes are executed.

Wait, isn’t JavaScript asynchronous and non-blocking?

Let me explain.

Synchronous nature brings certain problem

Synchronous feature brought poor user experience in certain condition. For example, when the code is requesting a large query from database, users need to wait until response reaches user-client.

Solution to behave asynchronously

A quick solution is to implement a call back queue. It means JavaScript identifies whether current function is a Web API or not. If it is, then it’s extracted from call stack to Web API, and the call stack will executes next line without waiting that Web API action to complete. JavaScript now behaves asynchronously and non-blocking.

When the extracted action completes, it is pushed into call back queue. Then, the action in call back queue will executed when call stack is empty.

So what is JavaScript again

JavaScript is a single-threaded synchronous language which could be manipulated to behave asynchronously.

Asynchronous also brings problem

There will be a time when we would like to wait asynchronous action to complete. For example, we surely want our code to wait for data query before performing operations on the data return.

This is where async/await and promises come in to play.

Simply put, async/await and promises are the features to tell JavaScript to wait until current asynchronous action completes.

So what is event loop?

Event loop is the secret that makes JavaScript behaves like asynchronous language. It is a mechanism to pull stuff from call back queue, and put it into call stack to execute.

--

--

Yu-Ming, CHANG (he/him)

I enjoy the positive mind flow when writing code to solve a problem. This is my journey to become a software developer, though now working as a product owner