Understanding JavaScript Execution Order 🤯

I'm Sandesh Shrestha, a passionate developer from India. Primarily interested in full-stack development and always exploring new technologies. Fascinated by science, space, technology, and ancient history. Love playing video games sometimes 🎮
Have you ever wondered how JavaScript manages to handle multiple tasks at once, despite being a single-threaded language? Let's embark on a journey to understand the inner workings of JavaScript's asynchronous nature by examining a curious code snippet.
Take a look at this piece of JavaScript code:
Promise.resolve()
.then(() => console.log(1));
setTimeout(() => console.log(2), 10);
queueMicrotask(() => {
console.log(3);
queueMicrotask(() => console.log(4));
});
console.log(5);
At first glance, it might seem like a jumble of functions and numbers, but fear not! Let's break it down together.
1. Promise.resolve() - Printing 1: When we encounter Promise.resolve(), JavaScript quickly resolves the promise and schedules the execution of its .then() callback. Since this is placed in the microtask queue, it takes priority over other tasks. So, console.log(1) cheerfully appears on our console first.
2. setTimeout() - Printing 2: Next up, we have a setTimeout() function, which schedules the execution of its callback after a minimum delay of 10 milliseconds. So, console.log(2) patiently waits on the callback queue until its time arrives.
3. queueMicrotask() - Printing 3 and 4: Ah, the microtasks! When we call queueMicrotask(), we're essentially saying, "Hey JavaScript, here's something important, please do it as soon as you can!" So, both console.log(3) and console.log(4) are placed in the microtask queue. Since microtasks are prioritized over macrotasks, they're executed promptly and in order. First, we get 3, followed by 4, just as we expected.
4. console.log(5) - Printing 5: Finally, we have a simple synchronous statement, console.log(5), which prints immediately without any fuss. After all, it's not asynchronous like our other friends.
So, when we put it all together, the output looks like this:
5
1
3
4
2
And there you have it! By understanding the core of JavaScript's event loop and task queues, we can better appreciate its asynchronous magic. So, next time you encounter asynchronous JavaScript, don't be afraid! You're equipped to decode the order of execution like a pro.
Keep coding and exploring the wonders of JavaScript! ❤️
Thanks to @LydiaHallie for explaining this topic on her youtube channel, Here is the link to her video.



