Behind the Scenes of JavaScript: What the Event Loop is and How it works

  

If you have started programming in JavaScript, sooner or later you will definitely have run into concepts like asynchrony, setTimeout, or Promise. Maybe you've noticed that code doesn't always execute in the exact order you wrote it in.

The culprit (or rather, the unsung hero) behind all of this is: the Event Loop.

Grab a coffee, get comfortable, and let's discover together how JavaScript manages to look like a multitasking expert while having only a single thread available.

🔗 Enjoying Techelopment? Check out the website for all the details!

The Big Misconception: JavaScript is "Single-Threaded"

There is only one golden rule to start with: JavaScript is single-threaded. This means that the JavaScript engine (like Google Chrome's V8) can execute only one thing at a time at any given moment.

Imagine being the only cashier in a crowded coffee shop: you can serve only one customer at a time. If a customer orders an elaborate coffee that takes time, what do you do? You can't block the entire line. You have to find a way to handle pending requests without stopping the world.

This is where the asynchronous architecture of the browser (or Node.js) comes into play, with the Event Loop acting as the conductor.


The Actors on Stage

To understand how the Event Loop works, we need to know the four main components of the system:

  • Call Stack: This is the cashier's whiteboard. The functions that JavaScript is executing at that precise moment end up here. It follows the LIFO rule (Last In, First Out): the last function to enter is the first to leave.
  • Web APIs (or Node.js APIs): These are tools provided by the execution environment (browser or Node.js). When you encounter a setTimeout, a fetch call, or an event listener, the engine offloads the "heavy" or "delayed" work to these APIs, immediately freeing up the Call Stack.
  • Task Queue (or Callback Queue): This is the waiting room. When an asynchronous operation (e.g., a setTimeout timer) finishes, its callback function is queued here, ready to be executed.
  • Microtask Queue: This is the express lane. Promise objects and mutation observers end up here. It has strict priority over the Task Queue.

How Does the Event Loop Dance Work?

The Event Loop's job is grueling yet incredibly simple. It boils down to an infinite loop that continuously does two things:

  1. Checks the Call Stack: Is it empty?
  2. If yes, it goes hunting for work in the queues. But pay attention to the order of priority:
    • First, it completely empties the Microtask Queue (executing all pending Promises).
    • Then, it takes just one element from the Task Queue (e.g., a setTimeout callback) and moves it to the Call Stack.

Repeat indefinitely.


Let's Get Our Hands Dirty: A Test for Experts (and the Curious)

To see if you've grasped the concept, take a look at this snippet of code. In what order do you think the messages will be printed to the console?

console.log('1: Start');

setTimeout(() => {
  console.log('2: Timeout completed');
}, 0);

Promise.resolve().then(() => {
  console.log('3: Promise resolved');
});

console.log('4: End');

If you thought of 1 -> 4 -> 3 -> 2, you hit the bullseye! Let's analyze why:

  1. console.log('1: Start') enters the Call Stack, is executed immediately, and printed.
  2. setTimeout is passed off to the Web APIs. The timer expires immediately (0ms), so its callback ends up in the Task Queue.
  3. The Promise.resolve().then(...) registers its callback in the Microtask Queue.
  4. console.log('4: End') enters the Call Stack and is executed immediately.
  5. The Call Stack is now empty! The Event Loop checks the queues. It finds the Microtask Queue with the Promise: executes it and prints "3: Promise resolved".
  6. Once the microtask block is finished, it moves to the Task Queue and prints "2: Timeout completed".

Conclusion

Understanding the Event Loop isn't just a theoretical indulgence for passing technical interviews; it's the keystone to writing high-performance JavaScript code, avoiding user interface freezes (the dreaded UI freezing), and debugging bugs related to race conditions or unexpected execution timing.



Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment