How JavaScript code is executed?

When we run the code a global execution context is created. Execution context is created in two phases i.e. memory creation phase and code execution phase.

Let’s understand this with the help of a program.

var x = 10;function square(num) {
var ans = num * num;
return ans;
var square1 = square(x);
var square2 = square(6);

In the first phase of memory creation, javascript will allocate memory to all the variables and functions.
JS will allocate memory to variable x and stores a special value that is undefined. In the case of function JS will allocate memory for square function and stores the whole code of the function inside the memory space.
Similarly will allocate memory for square1 and square2 variable and stores undefined for them.

The second phase is the code execution phase, this is the phase where every calculation of the program is done.
As it encounters the first line i.e. x = 10 it actually places the 10 inside the x. Till now the value of x is undefined but in the second phase x will be allocated 10.

For square1 here we are invoking a function and when we invoked a function a brand new execution context is created and again two phases will be involved. As soon as function execution is done will destroy the function execution context and will pass the execution back to the global execution context.