Home > Web Front-end > JS Tutorial > Why Do `let` and `const` Seem Not to Be Hoisted in JavaScript?

Why Do `let` and `const` Seem Not to Be Hoisted in JavaScript?

DDD
Release: 2025-01-03 02:29:40
Original
331 people have browsed it

Why Do `let` and `const` Seem Not to Be Hoisted in JavaScript?

Hoisting of Variables Declared with let or const

In ES6, variables declared with let or const appear to exhibit inconsistent hoisting behavior compared to var.

The Myth of Hoisting

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 Difference with let and const

The key distinction lies not in hoisting but in the initialization of let and const variables.

  • var/function/function*: These declarations are initialized with undefined or the function itself when the binding is created at the top of the scope.
  • let/const/class: These declarations remain uninitialized until the statement where they are defined is executed.

This temporal gap between the declaration and initialization creates the misconception about hoisting.

The Temporal Dead Zone

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.

Example

x = y = "global";
(function() {
    console.log(x); // undefined
    console.log(y); // Reference error: y is not defined

    var x = "local";
    let y = "local";
}());
Copy after login

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.

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template