In ES6, variables declared with let or const appear to exhibit inconsistent hoisting behavior compared to var.
First, it's important to clarify that all declarations in JavaScript are hoisted, including those using let, const, var, function, function*, and class. This means that all these declarations are visible throughout the scope they are defined in.
The key distinction lies not in hoisting but in the initialization of let and const variables.
This temporal gap between the declaration and initialization creates the misconception about hoisting.
For let and const variables, the period between the declaration and initialization is known as the temporal dead zone. During this time, accessing the variable results in a ReferenceError.
x = y = "global"; (function() { console.log(x); // undefined console.log(y); // Reference error: y is not defined var x = "local"; let y = "local"; }());
In this example, the var and let variables x and y are declared at the top of the function scope. However, the let variable y is not initialized until later, creating a temporal dead zone where accessing y throws an error.
While all declarations in JavaScript are hoisted, let and const variables exhibit a different initialization behavior. This behavior leads to the perception of "not being hoisted" but is in fact due to the temporal dead zone created by the late initialization. Both let and const variables work identically in terms of hoisting.
The above is the detailed content of Why Do `let` and `const` Seem Not to Be Hoisted in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!