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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

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

Okay