This content originally appeared on DEV Community and was authored by Diwakar Verma
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.
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.
This content originally appeared on DEV Community and was authored by Diwakar Verma
Diwakar Verma | Sciencx (2024-10-24T02:29:51+00:00) How Javascript works?. Retrieved from https://www.scien.cx/2024/10/24/how-javascript-works-3/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.