typeof 一个未定义的变量为什么是undefined而不是ReferenceError?
参考答案
因为 typeof 对未声明的标识符有特殊规则:规范要求 typeof x 在 x 无法解析时返回 'undefined',而不是抛 ReferenceError。
原因:为兼容早期代码(检测某个可选全局变量是否存在),如 if (typeof jQuery !== 'undefined')。
注意:
typeof对 let/const 的 TDZ 变量仍会抛 ReferenceError(因为已声明但未初始化);- 直接使用未声明变量
console.log(x)才会抛 ReferenceError。