声明前使用
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内访问let或const变量都会产生runtime error,只有遇到声明语句时才会把它从TDZ里移出并正常使用。
[JS] 关于变量作用域的 undefined 和 error
原文:https://www.cnblogs.com/wanyi/p/10361933.html