What is the Event Loop?

I am sure everyone who has worked with JavaScript is or was confused about how does JavaScript work ? Is JavaScript Synchronous or Asynchronous? What is the Event Loop? I think I have understood some parts of it and will try to share my learnings with you.

Lets start with JavaScript Runtime Environment. JavaScript Runtime Environment interacts with the Internet and helps the code work. This is the backend of the browsers which enables us to browse and interact with the websites. For example V8 Engine is the runtime on Chrome. Below is the simple view of the JavaScript Runtime Environment.

JSRunTime.png

As you can see the main components of JavaScript Runtime are the Memory Heap and the Call Stack. Memory Heap is where the memory allocation happens and the Call Stack which keeps track of operations being performed. But these are not the only components on which the browser runs. There are other components which are the Web API's, the Event loop and the callback queue.

Lets now look at how these components work together:

We all know that JavaScript is a single threaded language, it will do one thing at a time which implies that it has a single call stack. Call Stack is a data structure which records where in the program are we. When we execute a function we push the function into the stack and when the function execution is finished, we pop the function from the stack.

function multiply (x, y) {
    return x * y;
}

function square (n){
    return multiply(n, n);
}

function displaySquare(n){
    var squareResult = square(n);
    console.log(squareResult);
}

displaySquare(4);

Lets have a look at the call stack once we run the above code. The execution starts from the displaySquare() function, since the others are function declarations, so we push displaySquare(4) into the stack. stack.png

displaySquare(4) calls square(4) function which is pushed to the stack, similarly square(4) calls multiply(4,4) which is added to the stack. So our stack will look something like this.

stack.png

When multiply(4,4) executes the return statement, it is taken off from the stack. As stated earlier once the function finishes execution we pop it from the stack.

Even if you haven't visualized the call stack earlier in the above way, you might have come across it while doing browser side development.

image.png

This was the call stack for Synchronous code, lets have a look at how does the call stack behave for asynchronous code.

console.log('Opening ');

setTimeout(function () {
   console.log('Async Code');
   },5000);

console.log('End');

In the above code, the first line is executed immediately and has no dependencies so it is pushed and popped immediately from the stack. The setTimeout is an async function so it is pushed into the stack, but it disappears from the stack mysteriously. The last line also is pushed to the stack and popped after execution. Once the stack is empty the setTimeout appears in the stack and is popped after execution.

This is where Event loop comes into picture. We know that JavaScript runtime can do one thing at a time, but the browser gives us other things or API's which are effectively threads which we can make a call to and the browser will be made aware of this.

Now let us try to understand the above async code in which the setTimeout function mysteriously disappeared from the stack, setTimeout is a API provided by the browser, so once it is called the browser calls the API and it disappears from the stack while the browser handles the operation. Meanwhile the call stack runs the rest of the code.

JRE.png

The Web API waits for the timer meanwhile the rest of the code is executed. Once the timer goes off and the setTimeout callback function is ready to execute. This is where the task queue or the callback queue comes into picture. The Web API pushes the callback function to the queue when its done.

JRE.png

Finally we get to Event Loop which is the title of the article. Event loop is the simplest little piece in this whole equation which has a single job. It looks at the call stack and at the task queue. If the stack is empty it takes the first thing from the queue and pushes it to the stack.

amam.png

Let us try to summarize the whole equation.

asa.png

The call stack is a data structure that keeps track of where we are in the program and runs in a last-in, first-out way. Whenever an async function is called the call stack sends it to the browser API. Based on the command received from the call stack the API start its own operation thread. Once this operation is finished the API sends this operation to the Event Queue. The Event Loop monitors the Call Stack and the Event Queue and sends the first operation from the queue to the stack once the stack gets empty. This is the cyclic system to run async operations in JavaScript.