Well, have you ever wondered how a web browser works and our favourite Google search engine gives instantaneous and spontaneous results? Okay, this is not rocket science to not understand and not a piece of cake to easily understand. This marvel was created with only logic and coding. So in this article, I will explain to you the few basics of JavaScript that are one of the reasons behind working on web applications and the most awaited part, “Event Loops.”
A quick look at JavaScript
JavaScript plays a vital role in web browsing and is used in web development, web applications, gaming, etc. This is a dynamic language for any web developer since it is used for creating dynamic and interactive web functionalities. JavaScript embeds CSS and HTML, which can be updatable and changeable. JavaScript is a single-threaded language; that is, you can’t execute multiple codes in parallel when a certain code is executing. The reason for having a single-threaded stack in JavaScript is to reduce the complexity. So, unlike the other programming languages like Java, C, and C++, which work on multithreading, JavaScript refers to a single-threaded mechanism.
Event loop in JavaScript
JavaScript has a unique runtime model called the event loop, which is quite difficult for the rest of the languages. This event loop in JavaScript is responsible for code execution, event collection, processing, and also the execution of sub-tasks in a queue. Javascript is a non-blocking, asynchronous, and concurrent programming language. So whenever any asynchronous part of the code needs to be executed, JavaScript takes the help of the Web API and executes non-blocking and asynchronous codes. So, before delving into the mechanism of the event loop, let us first learn about JavaScript keywords and concepts.
[Also Read, Event Delegation in JavaScript]
Heap
Objects with a certain value are allocated in the heap with some memory. So basically, the heap is an area for the allocation of memory to objects and functions. The HEAP has no infinite space to allocate memory for every object and function, so there’s an occurrence of memory leaks in the heap when data overflows.
Stack
A stack is a place where all your programme lines get executed step by step. Remember that JavaScript is a single-threaded language, so at a time, only one line of code gets executed in the stack. When the part of the code needs to be executed, it is pushed into the stack, and once it is executed, it pops out of the stack. There are a few parts of the code that a stack of javascript can not execute, like setTimeout, ajax(), promise, or click event, which is part of the Web API. So if there’s an occurrence of Web API-oriented lines of code, the stack pops out the code that is executed by the Web API. So now the line of code gets into the Web API for execution.
Callback Queue
Previously, I have said that there are a few commands or code lines like setTimeout, ajax(), promise, or click event, executed by the Web API. These lines of code, which are associated with the Web API, enter the callback queue and wait for code execution.
[Also Read, JavaScript Coding Interview Questions and Answers]
Mechanism of the event loop
So let us try to illustrate the mechanism of the event loop in JavaScript with an example code.
console.log('First');
setTimeout(() => {
console.log('Second');
}, 1000);
console.log('Third');
Here we have considered a code which consists of console functions. So now let’s execute the above-illustrated code in JavaScript. in the console, you will get the output as below screenshot.
Now let’s understand the process, and how the code is executed.
- Push into the stack
console.log('First');
The first code line is pushed into the stack where it has to be executed. When the code is executed, it pops out of the stack and the result will be ‘First’.
- Code for Web APIs
If the code consists of commands like setTimeout, ajax(), promise, or click events that are needed to be executed by the Web API, then the stack pops the code out of the stack and the code is pushed into the Web API. Here is the code.
setTimeout(() => {
console.log('Second');
}, 1000);
It includes the setTimeout () function, which requires 1000ms in the Web API to enter the callback queue. After 1000ms, the code gets into the callback queue for execution.
- Callback queue
After 1000ms, the code line enters the callback queue. So let me make clear once again that it doesn’t mean the setTimeout() code gets executed soon after the 1000ms. It just gets added to the callback queue where it will add to the stack for the execution.
- Event loop
The event loop is the place where the execution of callback codes comes into action. You might be wondering how the callback queue and stack are connected and how the process of callback code is executed, right? Okay, let’s simply understand the process quickly.
The event loop’s main functionality is to check the stack constantly whether it is idle or busy. If the stack is empty or idle, then the event loop immediately calls the waiting code in the callback queue to enter the stack. So when the stack is empty with no further stack console executions, the first code in the callback queue is entered into the stack for execution. Again, the process is as follows: code is pushed into the stack, code is executed, and code is popped out of the stack. This is how the callback queue codes are executed in the Javascript stack. And the event loop is something that connects the stack and the callback queue. If the call stack is empty, the callback queue codes enter the stack and the code gets executed.
Okay, now you might be aware of the callback and event loop functionality in JavaScript. Let’s once again quickly wrap up the concepts.
- Objects and functions are allocated some memory in HEAP.
- The objects and functions enter the stack for code execution. Remember that Javascript is a single-threaded language, so only one line of code is executed at a time.
- The code is pushed into the stack, the code gets executed, and the code pops out of the stack.
- The WEB API code lines are something that cannot be run by the JavaScript engine. So these lines are popped out of the stack and turned to the WEB API.
- The web API finds the type of functionality in the code and does the process accordingly. For example, if it is the setTimeOut() function, then the web API waits until the prescribed completes and then the code is pushed to the CALLBACK QUEUE.
- The CALLBACK QUEUE collects the code lines that need to be executed by the call stack.
- The event loop connects the CALL STACK and CALLBACK QUEUE. If the call stack is empty, then the callback queue is connected to the stack and the first line of code from the queue is pushed into the stack for execution. The stack does the same thing for every line in the code; it executes the code and pops out the code after execution.