JavaScript Execution Context and Event Loop

JavaScript Execution Context and Event Loop

What happens when you run a javaScript program?

JavaScript is a single threaded programming language ( it has a single run time or a call stack) which means that it can run only one piece of code at a time. When you run a javaScript program , there are many things that happen behind the scenes . The first thing that happens is the creation of an execution context and everything in javaScript happens inside this execution context. So, let's dive deep into the understanding of Execution Context and see how the javaScript code is actually executed behind the scenes.

Understanding the javacript Ececution Context

The javaScript execution context is an abstract concept of an environment where the javascript code is executed and everything in javascript happens inside an execution context.

How is the Execution Context created?

The execution context in javascript is created in two phases 1) Memory creation phase. 2) Code execution phase.

Memory Creation Phase :-

In this phase , javascript runs through the whole program line by line and allocates memory to all the variables and functions in the form of key value pairs. When memory is allocated to the variables and functions , the main question that arises is; what does these variables and functions store? The answer is : in case of variables , the undefined value/keyword is stored initially as its value. In case of functions , the whole code of the function is stored as its value. Let's understand this phase properly with the help of an example.

var n = 10;
function square (num){
   return num * num ;
}
var squareTen = square(n);
var squareFive = square(5);

In the code above, javascript will start executing the code from top to bottom . So, when javascript encounters the first line, memory will be allocated to the variable n and it will store undefined as its value. After allocating memory to the variable n , javascript moves on to the second line where it encounters the function named square . So , memory will be allocated to the function square and it will store the whole code of the function square . Similarly at line number 5 and 6 , memory will be allocated to the variables squareTen and squareFive respectively and the undefined value will be stored in these variables. This is all that happens in the phase one ( Memory Execution Phase ) . Let's now see what happens in the second phase ( Code Execution Phase ).

Code Execution Phase :-

In this phase , javascript once again runs through the whole program line by line and the code is executed . In this phase , all the functions and calculations are done. In the code execution phase , when a variable is triggered , the undefined value which was stored in the variable in the memory creation phase is replaced by the actual value of that variable.

When a function is invoked , a brand new execution context called Functional Execution Context is created with the same two components/phases . In the first phase of memory creation, only the variables declared inside the invoked function are allocated memory with a value of undefined . Similarly , in the code execution phase , all the code inside the function is executed line by line and all the calculations are done. Based on these calculations , the undefined values are replaced by the calculated values .

The return keyword tells the function to return the control back to the global execution context where the function was invoked and the new functional execution context that was created as a result of functuon invokation is deleted. When all the lines of code are executed , the global execution context is also deleted.

Concept of Call Stack

To maintain all these things ( creation , deletion and control ) , the javascript engine uses a stack called call stack . Call stack is a data structure which records where in the program we are. It is like an actual stack of things built on top of each other and the global execution context is at the bottom of this stack. If we step in a function, we put something (push) on the stack . If we return from a function, we pop off from the stack.

Understanding Asynchronous JavaScript and the concept of Event Loop

By definition , JavaScript is a single threaded programming language ( it has a single run time or a call stack) which means that it can run only one piece of code at a time. But we have something called the Javascript runtime environment , it is like a big container which has all the things required to run a javascript code like a js engine, set of APIs , event loop , call back queue.

By your understanding of javascript execution context until now , you can declare that javaScript is synchronous and single threaded but, what if i tell you that you can do some things concurrently (at the same time) in javascript as the browser is more than just the run time javascript . The browser gives us some other things which help in doing things concurrently like Web APIs (DOM , AJAX , setTimeout). Let's understand this better with the help of an example .

console.log('Hi');

setTimeout(function cb( ) {

console.log(’there’);

} , 5000 ) ;

console.log(’other text’) ;

When we run this code , it will log Hi and clear the call stack. Then , it will call the setTimeout with a callback function and a delay of 5 seconds . As setTimer is an API provided by the browser, the browser will kick the setTimer for us because it is not completed yet. Then, it will log ‘other text’ and clear the call stack.

Now, we have got this timer in the web API stack which is going to complete after 5 seconds. The web API cannot modify the code ; so, when they are done , the callback is pushed on to the task queue and finally the event loop comes into play . The event loop works by checking if the call stack is empty or not . If the call stack is empty, it takes the first thing on the queue and pushes it onto the call stack which effectively runs it. Finally it will log ‘ there ‘. Even if we set the timer for 0 seconds, it will show the output the same way because the setTimer function is provided by the browser. It will get added to the web API stack and after that it will be added to the task queue. Then, the event loop will have to wait until the call stack is empty to add this particular function ( setTimer ) to the call stack.

Event Loop

An event loop is something that pulls stuff out of the task queue and places it onto the call stack whenever the call stack becomes empty. The event loop works by checking if the call stack is empty or not . If the call stack is empty, it takes the first thing on the task queue and pushes it onto the call stack which effectively runs it.