During the memory creation phase of the execution context, variables declared with let and const are allocated memory in the block scope, not in the global scope. These variables cannot be accessed before they are initialized. Here Temporal Dead Zone (TDZ) Comes To In Picture.
π Temporal Dead Zone In JavaScript :
Temporal Dead Zone is a behavior in JavaScript where variables declared with let and const are inaccessible before their initialization.
Temporal Dead Zone (TDZ) is the time period in JavaScript when a variable declared with let or const has memory allocated but has not yet been initialized.
π Explanation Of Above Example :
During the memory creation phase, memory space is allocated for the variable 'a'. However, 'a' is not initialized yet. This marks the beginning of the Temporal Dead Zone (TDZ) for variable 'a'. The Temporal Dead Zone (TDZ) ends when variable 'a' is initialized with the value 1.
Attempting to access 'a' variable in its TDZ will Throw a ReferenceError.
Similarly, the TDZ applies to _const _variables as well
π Explanation Of Above Example :
Here, a is properly declared and initialized before we attempt to access it, so there is no TDZ violation, and the value of a (which is 1) is successfully printed to the console.
In summary, the TDZ is a period during which let and const variables exist but are not yet accessible. The TDZ ensures that variables are accessed only after they have been properly declared and initialized,
Top comments (0)