Hoisting of Variables Declared with let or const
While variables declared with var behave as expected during hoisting, those declared with let or const exhibit different behavior.
Hoisting of All Declarations
All JavaScript declarations (var, let, const, function, function*, class) undergo hoisting, meaning they're recognizable anywhere within their respective scope.
Initialization Difference
However, the distinction between var/function/function* and let/const/class declarations lies in their initialization. Var declarations are initialized with undefined from the moment of binding creation at the scope's start. In contrast, let/const/class declarations remain uninitialized until their statement is evaluated.
Temporal Dead Zone for Uninitialized Variables
This uninitialized state creates a "temporal dead zone" where accessing the variable before initialization results in a ReferenceError.
Example:
x = y = "global"; (function() { x; // undefined y; // Reference error: y is not defined var x = "local"; let y = "local"; }());
let vs. const in Hoisting
Let and const operate identically in terms of hoisting. The difference between them is that a constant must always be assigned a value upon declaration.
Conclusion
Variables declared with let or const are hoisted, but they remain uninitialized within a temporal dead zone until their declaration statement is processed. Accessing them prematurely will result in a ReferenceError.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3