Skip to main content

Command Palette

Search for a command to run...

JavaScript Architecture - Event Loop Explained

Updated
2 min read
JavaScript Architecture - Event Loop Explained

Since in JavaScript we need to run code both synchronously and asynchronously it becomes very important for us as developers to understand how this entire JS code gets executed in the background.

In this article, we will understand in a step-by-step and detailed manner how JS executes our code.

In our browsers, we have something known as the JavaScript Engine.

The JavaScript Engine comprises 2 components:-

  • Heap

  • Call Stack

Heap stores functions and objects.

The call stack is the place where the real code execution takes place.

When we run a JavaScript code, JavaScript creates a Global Execution Context. By default, it is the synchronous code that gets executed first.

Then what happens to the asynchronous code?

The asynchronous code is handled by something called Web APIs. For eg. fetch(), setTimeout(), setInterval(), etc. all of these are handled by the Web APIs.

As soon as the response is fetched by fetch() or the timer returns a 0 in the case of, the callbacks enter a queue also known as Task Queue in the order of their completion.

As mentioned earlier, JavaScript first executes the synchronous code.

So, once the call stack is empty, the asynchronous code dequeues from the Task Queue, enter the call stack, and is finally executed.

But there is a catch!

Not all async calls enter the Task Queue. Promises are one such async call.

Many times Promises are chained to handle multiple asynchronous calls. (Promise Chaining). In JavaScript, promises are given higher priority than setTimeout().

So, to store promise callbacks, we use another queue called Micro Task Queue.

Note that the Micro Task Queue is always given higher priority than Task Queue.

This means when the call stack gets empty after finishing the execution of synchronous code, it is the callbacks in the Micro Task Queue which are first pushed into the call stack.

This also means that the callbacks in the Task Queue are the last to be executed.

This entire loop that we went through above, is called the Event Loop.

************************

I hope you found this article insightful.

Will meet you in the next one.

Happy reading!