面试题:typeof null 的结果是什么?为什么?

typeof null 的结果

typeof null 的结果是 "object"

这是一个在 JavaScript 早期就存在的历史遗留 bug


为什么是 "object"

1. 历史原因(C 语言风格的实现)

JavaScript 的最初版本(由 Brendan Eich 在 1995 年用 10 天设计)中,每个值都用一个类型标签(type tag)和实际值来表示。这些标签是:

  • 000:对象
  • 001:整数
  • 010:双精度浮点数(数字)
  • 011:字符串
  • 100:布尔值
  • 101:null
  • 110:undefined
  • 111:符号(Symbol)

null 的类型标签是 101

问题来了:当使用 typeof 检查一个值时,它会读取这个类型标签。但 null 的内部表示恰好是全零的机器码(即所有位都是 0)。

在检查时,JavaScript 引擎错误地将 null 的全零位模式当成了对象类型标签000),因此 typeof null 返回了 "object"

2. 无法修复的兼容性问题

这个 bug 在 JavaScript 的第一个版本发布后就被发现了。但由于当时已经有大量代码依赖这个行为(即使它是错误的),修复它会导致成千上万的网站崩溃

为了保持向后兼容性,这个 bug 被保留了下来,并成为了 JavaScript 语言的一部分。


示例

typeof null        // "object"
typeof {}          // "object"
typeof []          // "object"
typeof new Date()  // "object"

// 但 null 并不是对象!
null instanceof Object  // false ← 正确的行为

如何安全地检查 null

由于 typeof null === "object",不能用 typeof 来区分 null 和其他对象。应该使用严格相等

if (value === null) {
  console.log("value is null");
}

// 如果要同时检查 null 和 undefined
if (value == null) {
  // 会匹配 null 和 undefined
}

// 或者分别检查
if (value === null || value === undefined) {
  // ...
}

总结

  • 结果typeof null 返回 "object"
  • 原因:这是 JavaScript 早期实现中的一个历史 bug,由于 null 的内部表示是全零,被错误地识别为对象类型标签。
  • 现状:由于向后兼容性,这个 bug 被永久保留。
  • 最佳实践:使用 === null 来检查 null,而不是依赖 typeof
THE END
喜欢就支持一下吧
点赞15 分享