ES6 type causes error

ES5 typeofis considered safe because it does not throw ReferenceErrorwhen re-checking an undeclared value. such as

console.log(typeof undeclaredVar); // undefined

However, when checking typeof undeclaredLetConstin es6, it will only throw an error if the value was later declared using letor const. if it was declared with var, it will work fine.

console.log(typeof undeclaredLetConst);
let undeclaredLetConst = "hello";  // ReferenceError

What is happening there?

+4
source share
1 answer

Why does it work with ads var

JavaScript var, ( , "use strict").

, typeof , , , .

(TDZ)

TDZ ECMAScript, , let const .

const let

JavaScript let const, TDZ. TDZ .

TDZ , .

console.log(typeof undeclaredLetConst);     // "undefined"

if (1) {
    let undeclaredLetConst = "no errors!";
}

undeclaredLetConst isnt TDZ, typeof, , undeclaredLetConst. , , typeof "undefined".

: . , ECMAScript 6.

+9

Source: https://habr.com/ru/post/1654217/


All Articles