Home > Web Front-end > JS Tutorial > How Do `let` and `const` Differ from `var` in JavaScript Hoisting?

How Do `let` and `const` Differ from `var` in JavaScript Hoisting?

Barbara Streisand
Release: 2024-12-31 04:18:12
Original
308 people have browsed it

How Do `let` and `const` Differ from `var` in JavaScript Hoisting?

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";
}());
Copy after login

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.

The above is the detailed content of How Do `let` and `const` Differ from `var` in JavaScript Hoisting?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template