How Javascript works?

Diwakar Verma - Oct 24 - - Dev Community

When you run JavaScript code, an execution context is created. This context is like an environment where your code is executed. Each time JavaScript encounters variables or functions, it creates execution contexts to manage them.
Image description
Step 1: Global Execution Context
When the code starts running,the Global Execution Context is created. This has two phases:

Creation Phase:
JavaScript allocates memory for variables and functions.
In this phase, variables are set to undefined, and function declarations are stored in memory.
So, after this phase x is stored as undefined.The entire add function is stored in memory(not executed yet).
Execution Phase:
Now, the code runs line by line.
When it reaches var x = 5;, the value of x is updated from undefined to 5.

Step 2: Function Execution Context
When JavaScript hits add();, a new execution context is created for the add function. This works the same way.

Creation Phase

The local variables in add (in this case, y) are initialized with undefined.
So, inside add(): y is initially undefined.
Execution Phase

JavaScript runs the function’s code.
The value of y is set to 10 (from undefined).
The return statement return x + y; is executed, and since x is 5 (from the global context) and y is 10, it returns 15.

This is how a code works in JavaScript.

. . . . . . . . . . . . . .
Terabox Video Player