How is Javascript Code Executed??

Hemant prajapati
2 min readApr 26, 2023

--

So as we discussed in the last post Everything happens in Javascript inside Execution Context. so here in this post, I am going to explain to you how is javascript code Executed. So as we know Execution Context has two things first one is the variable environment and second is Thered which is also known as Theded of Execution where code runs.

So in this post, we play around with the Execution Context of How the Javascript code runs and what exactly happens so are you ready to drive inside the javascript?

So here we go starting with some code for more understanding i have written some code that help you to better to get the concept of Two phases of Execution Context.

var n=4;

function square(n){
var ans =n*n;
return ans;

}
var square2=square(2)
var square4=square(n)

In the above code, you might not understand why I am writing the code and how it will help me to get more understanding of the javascript. So basically in the Execution Context there are two phases first memory allocation phase and the second code execution phase.

As i previously tell that in the variable environment variable is assigned with key-value pair in the first phase of memory allocation the above code variable is assigned with the undefined and the function will be assigned of the whole code. this sound might confusion.

this is the first phase when the javascript code runs it will create a memory allocation for the variable and the function but in the case of the function, it will assign the whole code. From here the interesting story starts when the function invokes then again the Execution context will be created for the function and whatever variable is stored inside the function again the same thing happens the variable is first assigned with undefined which is the above code. also, one thing the parameter as well assigned is undefined in the first phase

Now it is time to the Second Phase which is Code of Execution where the codes where when the function invokes that time n which has 2 which replace with undefined and passes from the parameter to ans where ans which is assigned with undefined now has 4 values because of replacing the values. Now the function will return to the square2 variable of ans variable value. This is how everything will replace with the actual value .

--

--