What is the Temporal Dead Zone (TDZ)?
const are not accessible before their declarations in the code.
Consider this code snippet:
console.log(x); // Throws a ReferenceError let x = 10;
In this example, even though
x is declared later in the code, trying to access it before the declaration will result in a ReferenceError due to the TDZ.
How does the Temporal Dead Zone work?
Hoisting is a behaviour where variable and function declarations are moved to the top of their containing scope during compilation, but the assignments (the initializations) are not moved. This means that while the variable declaration is hoisted, its assignment is not, and that's what creates the Temporal Dead Zone.
Here's what happens step by step:
constdeclaration and allocates memory for the variable but doesn't assign a value to it.
The variable is added to the scope, and the Temporal Dead Zone begins.
Any attempt to access the variable during the TDZ results in a ReferenceError.
Once the program execution reaches the actual variable declaration, the variable is assigned the specified value, and the TDZ ends.
Why it does not happen with
Variable Declaration and Initialization with
var: When you declare a variable using
var, it is both declared and initialized at the top of its containing function or global scope during the hoisting phase. This means that a
varvariable is automatically assigned a default value of
undefinedat the beginning of its scope. This initialization ensures that you can access and use
varvariables before their actual declaration in the code.
const: In contrast, variables declared using
constare hoisted differently. While they are still hoisted to the top of their containing scope during the hoisting phase, they are not initialized. Instead, they enter the Temporal Dead Zone (TDZ) until their actual declaration in the code. During the TDZ, attempting to access or use these variables results in a ReferenceError.
const to take full advantage of block scoping while avoiding the pitfalls of the Temporal Dead Zone.