Skip to content

JavaScript-TDZ与变量提升 #1

Open
@renjie1996

Description

@renjie1996

JavaScript-TDZ & 一次混淆

let会不会把变量提升

image

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

    var x = "local";
    let y = "local";
}());

The difference between var/function/function* declarations and let/const/class declara­tions is the initialisation.

MDN let文档

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

TDZ 临时死区

  1. No Redeclaring
  2. In ECMAScript 2015, let bindings are not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a ReferenceError (contrary to a variable declared with var, which will just have the undefined value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

image

Notice that in terms of variables lifecycle, declaration phase is a different term than generally speaking variable declaration. In simple words, the engine processes the variable declaration in 3 phases: declaration phase, initialization phase and assignment phase.

image

Suppose a scenario when JavaScript encounters a function scope with var variable statement inside. The variable passes the declaration phase and right away the initialization phase at the beginning of the scope, before any statements are executed .

image

If you try to access variable at this stage, JavaScript will throw ReferenceError: variable is not defined. It happens because the variable state is uninitialized.
variable is in the temporal dead zone.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions