typeof 运算符的执行顺序

理解 typeof 的链式调用和函数返回值的类型判断

问题

下面代码的输出是什么?

console.log(typeof typeof typeof null);
console.log(typeof console.log(1));

解答

第一行代码

typeof typeof typeof null 输出 "string"

执行过程:

  1. typeof null 返回 "object"(JavaScript 的历史遗留问题,null 被视为空对象引用)
  2. typeof "object" 返回 "string"
  3. typeof "string" 返回 "string"

第二行代码

typeof console.log(1) 先输出 1,然后输出 "undefined"

执行过程:

  1. console.log(1) 先执行,输出 1
  2. console.log() 没有返回值,返回 undefined
  3. typeof undefined 返回 "undefined"

完整输出

string
1
undefined

关键点

  • typeof 运算符返回的是字符串类型,所以 typeof 任何字符串都返回 "string"
  • typeof null 返回 "object" 是 JavaScript 的已知 bug,但为了向后兼容一直保留
  • console.log() 没有返回值,默认返回 undefined
  • 函数调用会先执行,再对返回值进行 typeof 运算