var
Scope
As we all know, there isn’t block-level scope but function-level scope in JavaScript.
For example:
|
|
Hoisting
Moreover, declaring a variable at anywhere is equivalent to delcaring it at the top (of the function or global) in JavaScript, which is called hoisting.
For example:
|
|
let and const
scope
ECMAScript 2015 (aka ES6) introduced two ways to declare block-level scope local variables: let
and const
. let
‘s function is likes var
, and const
declares read-only value.
|
|
Hoisting
Variables declared by let
and const
will also be hoisted to the top of the blocks. But unlike var
, referencing the variables declared by let
and const
before their declarations will result in a ReferenceError
because of the TDZ (Temporal Dead Zone, the region of a program, where a variable or a parameter cannot be accessed until it’s initialized).
The specification says:
let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment. The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer’s AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.
Examples:
|
|
BTW, TDZ is not implemented in most transpilers (like babel, traceur), an issue. :cold_sweat: