Introduction
Hello friends, in this article, we will learn about the event loop and how the event loop works and you will also develop a good insight into how javascript code runs. Event Loop is one of the most important topics in JavaScript, and this topic is mostly asked in the interview process.
In my previous article, we discussed synchronous and asynchronous programming in JavaScript, and we have seen how in asynchronous, there is no blocking of the main thread, and all the statements or the program works in the background or parallelly without waiting for a particular task to complete.
Let us understand how JavaScript is a single-threaded language that can handle multiple operations asynchronously under the hood.
Table of contents
- Working of JavaScript
- Working on Javascript Engine
- Working on Event Loop
- Conclusion
Working of JavaScript
You must be aware; if not, let me tell you JavaScript works on the client and server sides. Now you must be thinking about how JavaScript can work on both client-side as well as the server side.
So basically, we use NodeJS to run JavaScript on the server side, and on the client side, we use Web Browsers to run the JavaScript code.
Now you must be thinking how NodeJS and web browsers can run the JavaScript code, so basically, they use a JavaScript runtime engine behind the scene, and that's how they can process or run the JavaScript code on the server side as well as on the client side.
Now for the server side, NodeJS uses V8 Engine to run JavaScript programs, but on the client side, let us know about the different JavaScript runtime engines used by different browsers.
- V8: Open-source JavaScript Engine developed by Google for Chrome
- SpiderMonkey: The JavaScript Engine powering Mozilla Firefox
- JavaScriptCore: Open-source JavaScript Engine developed by Apple for Safari
- Rhino: Open-source JavaScript Engine managed by Mozilla Foundation for Firefox
- Chakra: A JavaScript Engine for Microsoft Edge
- JerryScript: A JavaScript engine for the Internet of Things (Iot).
Note. The above-given JS engine is used by respective browsers, and with their help, only the browsers can run the JavaScript code on the client side, and NodeJS uses V8 Engine to run the JavaScript code on the server side.
Did you ever know these things earlier? Let's stick to this article to find out more amazing things about javascript.
Now we understand that with the help of the JS engine, we can run the JavaScript code on the client and the server side. Now let us look inside the engine. How does this engine process the JavaScript code? If you have seen my previous article in which I discussed asynchronous and synchronous, we found that JavaScript is a single-threaded language it can run multiple tasks at the same time without even waiting for a task to complete.
Let us know how the JavaScript Engine does that.
Working on JavaScript Engine
So in this section, we will be taking examples of the JavaScript V8 Engine, and we will see how the V8 engine runs the JavaScript code in the Browser and on the server.
Just to give you a basic idea, whenever we launch our Browser or run NodeJS, the V8 engine is executed, and it gets initialized and creates an environment to process JavaScript code.
Now the environment provides everything a JavaScript engine relies on to run the JavaScript code on the server as well as on the client side, including,
- Call Stack
- Heap
- Callback Queue
- Event Loop
- Web APIs (on the client side) / Node APIs (on the server side)
Now let us get the basic idea of these terms:
- Call Stack: The call stack in JavaScript keeps track of function calls and the order for executing and returning the output.
- Heap: The heap in JavaScript is used for memory allocation and storing objects and variables.
- Callback Queue: The callback queue in JavaScript holds the function in a queue which is required to be executed once the call stack is cleared.
- Event Loop: The event loop in JavaScript is responsible for managing the execution of a synchronous task and handling the callbacks.
- Web APIs: Web APIs in JavaScript provides an interface to interact with browser features such as making network requests, running timers, DOM Manipulation, etc.
- Node APIs: Node APIs provide interfaces to interact with different system-level functionalities, such as file system operations, networking, etc.
Working on Event Loop
Before we understand the working of the event loop, let us first understand the below diagram to figure out where the event loop is in the environment and what it does.
Now if you look at the diagram, you will get a sense of what happens behind the scenes on the client side as well as the server side.
Call Stack
Call Stack is where all our JavaScript code gets executed one by one as the interpreter reads our program, and it gets cleared or removed whenever the program is executed or completes its tasks. Our call stack keeps track of the current running javascript program.
Let us understand this by an example.
console.log(‘Hello’);
If we try to run the above program, it will be executed by our call stack and print hello in our console window.
Let us try to understand by another example.
setTimeout(function () => {
console.log(‘Hello after 5 sec’);
}, 5000);
If we try to run the above program, the call stack will run the program, and it will see setTimeout() is declared so that it will send the setTimeout() function to the Web API, and the Web API will start the timer for 5 seconds and when's the timer is completed the console.log will be sent to the callback queue and our event loop will keep checking if our call stack is empty or not and accordingly it will process the message whenever the call stack gets empty, and we will be able to see the message in the console window, and this is how the asynchronous callback functions are executed by JavaScript.
From the above example, we can understand the importance of the event loop and how it keeps checking if there is a pending item in the callback queue or not and keeps checking if the call stack is empty or not and, accordingly, how it processes the callback queue items inside the call stack.
Event Loop
So basically, the event loop is a mechanism in JavaScript that is responsible to handle an asynchronous operation and ensure non-blocking execution, and managing the callback functions. It is responsible to maintain a queue of tasks and execute them one by one and return the control to the main program after every task. This gives JavaScript the capability to handle events timer and asynchronous operation efficiently in the background, and this is why it is able to run multiple tasks at the same time, even being a single-threaded language.
As the name suggests, the Event Loop keeps on running in a loop and continuously checks for pending tasks and executes them whenever the call stack is empty and keeps on repeating this process. This is how it enables JavaScript to handle concurrent operations and maintain responsiveness in web browsers as well as in the NodeJS environment.
Conclusion
In this article, I have tried to cover the working of the event loop, how JavaScript works, the different JavaScript engines, and how JavaScript can run multiple tasks or different sets of operations, even a single-threaded language. We also came to know how JavaScript works on the client side as well as on the server side.
If you have any questions, please drop comments, and I'll be happy to explain it to you.