Event Loop in JavaScript

Event Loop is a fundamental concept in JavaScript that enables asynchronous programming. This blog post explores how the event loop works and its significance in managing tasks and callbacks.
The event loop is responsible for handling asynchronous operations in JavaScript, allowing non-blocking execution of code. It works in conjunction with the call stack, web APIs, the micro and macro task queue to manage the execution of functions.
Micro tasks are Promises, queueMicrotask, Mutation Observers, and process.nextTick in Node.js. Macro tasks include setTimeout, setInterval, setImmediate, I/O operations, and UI rendering.
In Promises, then, catch, and finally each schedule a new microtask, and every await also schedules a new microtask.
Let's see an example to illustrate how the event loop works in JavaScript.
console.log("Start"); //Macro Task setTimeout(() => { console.log("Timeout Callback"); }, 0); //Micro Task Promise.resolve().then(() => { console.log("Promise Callback"); }); console.log("End");
So the output of the above code will be:
Start End Promise Callback Timeout Callback
setTimeout is set with a delay of 0 milliseconds, which adds the callback to the macro task queue.but what about:
new Promise((resolve) => { console.log("4"); //this is synchronous resolve(null); }).then(() => { console.log("5"); //this is asynchronous (micro task) }); console.log("6");
The output of the above code will be:
4 6 5
then callback is added to the micro task queue.let's see another example:
(async () => { console.log("8"); //this is synchronous await null; //this is asynchronous (micro task) so rest of the function will be added to micro task queue console.log("9"); })(); console.log("10"); //this is synchronous
The output of the above code will be:
8 10 9
await null causes the function to pause, and the rest of the function is added to the micro task queue.what about this one:
queueMicrotask(() => { console.log("6"); //this is asynchronous (micro task) queueMicrotask(() => { console.log("7"); //this is asynchronous (micro task) }); }); console.log("8"); //this is synchronous
The output of the above code will be:
8 6 7
queueMicrotask callback is added to the micro task queue.The event loop is a crucial part of JavaScript's concurrency model, enabling asynchronous programming by managing the execution of tasks. Understanding how the event loop works, along with the call stack, web APIs, and task queues, is essential for writing efficient and responsive JavaScript applications. By leveraging the event loop effectively, developers can create non-blocking code that enhances user experience and application performance.