[JS] 关于变量作用域的 undefined 和 error

在代码块外

声明前使用

a
> Uncaught ReferenceError: a is not defined

声明前用typeof

typeof b
> "undefined"

声明未赋值就使用

var c;
c
> "undefined"

在代码块内

没有声明就用

if (true) {
    a;
}
> Uncaught ReferenceError: a is not defined
if (true) {
    typeof a;
}
> "undefined"

声明前调用/用typeof

if (true) {
    a;
    let a = 10;
}
> Uncaught ReferenceError: a is not defined
if (true) {
    typeof a;
    let a = 10;
}
> Uncaught ReferenceError: a is not defined

分析

在代码块内,JS引擎遇到 var时会把它提到代码块最前,遇到let或者const时会把它加入到暂时性死区(Temporal Dead Zone),在TDZ内访问letconst变量都会产生runtime error,只有遇到声明语句时才会把它从TDZ里移出并正常使用。