What the heck is execution context in JS?? How JS code is executing under the hood??

What the heck is execution context in JS?? How JS code is executing under the hood??

Now we all know that Javascript is a synchronous single-threaded language. Everything in JS happens inside of the execution context. So what the heck is execution context? Let's see this today.

First and foremost we will take an example of code :

var x = 9;
function sum(num){
      var ans = num + num;
      return ans;
}
var sum1 = sum(x); 
......

Initial Global Execution Context :

IMG_64E058635E99-1.jpeg

At first A global execution context has been created and pushed onto the call stack. The initial Global Execution context has 2 separate blocks, memory and code. Every execution context is having 2 phases. In the first phase memory will be allocated.

Phase 1 : Memory Allocation

So after the first phase, our execution blocks will look:

IMG_6CB756BE3396-1.jpeg

So we can see here for x and sum1 variable, memory will be allocated and initial values of those will be undefined, but for the case of function sum, the whole function declaration will be saved inside the memory. Here is the difference we can see in JS from any other programming language.

Phase 2: Code execution

In this phase, our code will start executing line by line, top to bottom. But there is another twist. The first variable x will get the value 9 in place of undefined. In the next line sum function declaration will be skipped as it is already there in memory. But in line no 3, for the function call of sum, a new local execution context will be created and pushed on top of the Global execution context in the call stack.

IMG_DEA2B6C149F9-1.jpeg

In the initial phase of the local call stack, num and ans will be allocated memory and values will be undefined.

In the 2nd phase(code execution phase) num will have the value 9 and ans will be calculated and will be assigned 18.

Then when the execution pointer sees the return statement, the local execution context will be pulled out from the call stack and the value 18 will be stored inside the sum1 variable.

IMG_C9F540CD289F-1.jpeg

After this, it returns to the Global context and starts executing the next lines of code.