How JavaScript Works Behind the Scene
As a JavaScript developer, we should learn how JavaScript and the event loop works. What is the event loop? How does JavaScript code run behind the scene? In simple terms, the event loop is a JavaScript mechanism that handles asynchronous operations and allows JavaScript code to be non-blocking despite being single-threaded. So what does this mean? It means it can handle multiple tasks without freezing up, even though it can only execute one piece of code at a time. In simple terms, what are we talking about? Imagine we have only one chef but they're able to handle multiple customer orders at the same time.
How JavaScript Works Behind the Scene Memory Heap - Stores the primitive and non-primitive types and values such as string, boolean, bigInt, number, null, undefined, symbols. For non-primitive types there are a lot, but I will list some common ones: array, object, function, Date, RegExp, Set, etc. Call Stack - Where the code is executed synchronously. Web APIs - Where asynchronous operations happen. It checks APIs such as setTimeout, geolocation, fetching, DOM events, etc. Callback Queue - Holds callbacks from completed operations. It determines which queue they belong to: either task queue or microtask queue. Microtask - Holds the code with priority in the callback lane: .then(), .catch(), .finally(), queueMicrotask(), MutationObserver, and many more. Task Queue - The APIs that have intervals or delays that are not included in the microtask queue. Event Loop - Continuously checking if the call stack is empty. Lastly, display the result in the console
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => {
console.log("C");
setTimeout(() => console.log("D"), 0);
});
queueMicrotask(() => console.log("E"));
(async () => {
console.log("F");
await null;
console.log("G");
})();
console.log("H");Output: A F H C E G B D
Why this order:
1. Call stack (sync code): A, then F (an async function runs synchronously until its first await), then H. 2. Microtask queue: This queue drains completely before any task runs, in the order items were queued. That gives C (the .then), then E (queueMicrotask), then G (the code after await is queued as a microtask). 3. Task queue: B was queued first. D was queued later, from inside the C microtask, so it runs last.
Comments
No comments yet — be the first to say something.