Home > Article > Web Front-end > Temporal Dead Zone (TDZ) and Hoisting in JavaScript:
Temporal Dead Zone (TDZ) and Hoisting in JavaScript:
Example:
console.log(myVar); // undefined
console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
var myVar = 5;
let myLet = 10;
In the above example, myVar is declared using var, so it gets hoisted and initialized to undefined. But myLet is in the Temporal Dead Zone until its declaration, so trying to access it before the declaration throws a ReferenceError.
Key Points about TDZ:
Variables declared using let or const are not accessible before their declaration within a block scope, even though they are hoisted.
This prevents the usage of variables before they are explicitly initialized.
Example:
console.log(myVar); // undefined
var myVar = 5;
In the above example, the declaration of myVar is hoisted to the top, but its initialization (myVar = 5) remains at the place where it was written. So, when console.log(myVar) is called before initialization, it returns undefined.
Hoisting of var, let, const, and functions:
var: Variables declared with var are hoisted and initialized with undefined.
console.log(myVar); // undefined
var myVar = 10;
let and const: Variables declared with let and const are hoisted but are not initialized. They remain in the TDZ until their initialization.
console.log(myLet); // ReferenceError
let myLet = 20;
Function declarations: Function declarations are fully hoisted, meaning you can call the function even before the point where it's declared in the code.
myFunc(); // "Hello!"
function myFunc() {
console.log("Hello!");
}
Key Differences Between Hoisting and TDZ:
Hoisting lifts variable and function declarations to the top of their scope.
The Temporal Dead Zone occurs for let, const, and class, where the variables are hoisted but cannot be accessed until they are initialized. This prevents accessing variables before their declaration.
The above is the detailed content of Temporal Dead Zone (TDZ) and Hoisting in JavaScript:. For more information, please follow other related articles on the PHP Chinese website!