跳到主要内容

nullundefined 的区别是什么?

面试速答(30 秒版 TL;DR)

  • undefined 更像“缺失/未赋值”(系统默认、自然产生)。
  • null 更像“刻意置空”(开发者主动表达没有值)。
  • 它们都表示“空”,但语义不同;== 下它们相等:null == undefinedtrue,而 === 下不相等。

语义与常见来源

undefined 常见出现点

  • 变量声明未赋值:let a; // undefined
  • 读取不存在的属性:obj.notExist // undefined
  • 函数未传参:fn(x) {} 调用 fn()x === undefined
  • 函数没有 return:返回 undefined

null 常见出现点

  • 你主动表达“这里本来应该有值,但现在没有”:例如“清空选择项/清空引用”
  • 某些 API 约定返回 null 表示“没有结果”

typeof / 比较行为

typeof undefined; // "undefined"
typeof null; // "object" (历史遗留)

null == undefined; // true
null === undefined; // false

工程建议:

  • 判断 nullx === null
  • 判断 undefinedx === undefined(或更常见:typeof x === "undefined" 在某些边界更稳)
  • 需要同时覆盖 null/undefinedx == null(这是少数合理用 == 的场景)

JSON 序列化差异(很常考)

JSON.stringify({a: undefined}); // "{}"(undefined 会被丢弃)
JSON.stringify({a: null}); // "{"a":null}"

JSON.stringify([undefined]); // "[null]"(数组里的 undefined 变 null)
JSON.stringify([null]); // "[null]"

典型题 & 标准答法

Q1:为什么有两个“空值”?

  • undefined 用来表达“缺失/未初始化”的运行时状态(很多地方由语言机制自然产生)。
  • null 用来表达“这里应该有值,但我明确把它置空”这一语义。

Q2:什么时候用 null,什么时候用 undefined

  • 接口/协议层:尽量统一约定(例如“缺字段=undefined,字段存在但空= null”)。
  • JS 代码里:更推荐用 undefined 表示“可选”,用 null 表示“显式清空”。

易错点/坑

  • 认为 null 是对象:不对,typeof null 的结果是历史 bug。
  • x || defaultValue 会把 null/undefined/0/""/false 都当成“没有”,更稳的是 x ?? defaultValue(只把 null/undefined 当空)。

速记要点(可背诵)

  • undefined:缺失/未初始化;null:主动置空。
  • null == undefined 为真;判断可用 x == null 同时覆盖两者。