DEV Community

Cover image for Do you know how the code you write in JavaScript gets executed? How JavaScript supports asynchronous execution?
Afnaan
Afnaan

Posted on

Do you know how the code you write in JavaScript gets executed? How JavaScript supports asynchronous execution?

JavaScript is quite unique in that it’s single-threaded, meaning it processes code in a specific order. But despite this, it manages to handle time-consuming tasks without freezing up. So, how does it do that? Well, let me break it down for you.

First off, there’s the call stack. Think of it like a stack of plates in a kitchen, where each plate represents a function being executed. When a function is called, a plate is added to the stack. Once that function finishes, its plate is removed. And it operates on a last-in, first-out basis.
Then, there’s the event loop. This is JavaScript’s way of handling asynchronous tasks. It keeps an eye on the call stack, a queue for bigger tasks (macrotasks), and another queue for smaller, immediate tasks (microtasks). It checks if the call stack is empty. If it is, it grabs the first task from the microtask queue and puts it on the stack. It keeps doing this until the microtask queue is empty, and only then does it move on to the macrotask queue.

Speaking of queues, there are macrotasks and microtasks. Microtasks are for urgent stuff, like Promise callbacks, while macrotasks are for things like I/O operations or timers. And microtasks always come before macrotasks, affecting the order of execution.

Lastly, there’s the Web API stack, which is part of the browser. When you use functions like setTimeout, they’re handed off to this stack. Once the specified time elapses, the callback function gets added to the macrotask queue. It’s kind of like waiting for a timer to go off before doing something else.

In a nutshell this happens:
Code execution in JavaScript flows from the call stack ➔ to the event loop ➔ where microtasks take priority over macrotasks ➔ ultimately handling asynchronous tasks while synchronous code continues to execute.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay