Hi @Yunfei_Xie !!
let when it comes to hoisting.
For variables declared with
var, the declaration is hoisted to the top of the current scope, but the initialization (assignment) remains in place. This means that the variable is hoisted with an initial value of
undefined until the assignment is encountered in the code.
console.log(x); // Outputs: undefined
var x = 5;
In the above example, the variable
x is hoisted to the top, but its value is
undefined at that point. The assignment
x = 5 happens later in the code.
On the other hand, variables declared with
const are also hoisted to the top of the current scope, but they are not initialized (unlike
var). This is called the “temporal dead zone” (TDZ). If we try to access a
const variable before its declaration, we’ll encounter a
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 5;
In the example above, trying to access the variable
y before its declaration results in a
ReferenceError because the TDZ prevents accessing the variable until it’s fully declared.
In summary, both
let declarations are hoisted to the top of their scope, but
var variables are initialized with
let variables (and
const variables) are not initialized until their declaration is reached. The TDZ for
const variables provides a more strict behavior, avoiding accidental use before the declaration and promoting better code practices.
I hope it helps. Happy Learning