When node index.js is run, JavaScript creates a Global Execution Context for the index.js file. This context consists of two main phases:
2. Memory Creation Phase (also known as the "Creation Phase")
In this phase, the JavaScript engine scans the entire code and sets up the memory for variables and functions before actual code execution.
Hoisting takes place during this phase, where all variable and function declarations are processed at the top of their scope.
Variables declared with let and const are initialized in memory with a value of undefined but are placed in a "temporal dead zone" (TDZ) until the line where they are assigned a value.
Functions declared with the function keyword are fully hoisted and can be called before they are defined in the code (although this does not apply to functions defined using let, const, or arrow functions).
let a = 10;
Welcome Here, ${a}
console.log();
During the Memory Phase:
a is placed in memory, but because it’s defined with let, it is initialized with undefined in the TDZ.
3. Code Execution Phase (also known as the "Execution Phase")
After the memory setup, JavaScript starts the Code Execution Phase, where it executes the code line by line from top to bottom.
During this phase, JavaScript assigns values to the variables and executes any functions that are called.
In the case of index.js:
Line 1: let a = 10; – a is assigned the value 10.
Line 2: console.log(\Welcome Here, ${a});– This line prints Welcome Here, 10
to the console.
Key Points - **
**Temporal Dead Zone (TDZ): Variables declared with let and const are hoisted but remain uninitialized (in TDZ) until their definition is encountered in the code. This is why let and const cannot be accessed before they are defined, unlike var.
Global Execution Context: This context persists until the entire program has executed. Each time you invoke a function, a new Execution Context is created specifically for that function.
Scope Chain and Lexical Environment: The global context maintains a reference to the global scope, and each execution context has access to variables defined in its own scope as well as in its outer (lexical) scope.
Top comments (0)