null 和 undefined 的区别是什么?
面试速答(30 秒版 TL;DR)
undefined更像“缺失/未赋值”(系统默认、自然产生)。null更像“刻意置空”(开发者主动表达没有值)。- 它们都表示“空”,但语义不同;
==下它们相等:null == undefined为true,而===下不相等。
语义与常见来源
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
工程建议:
- 判断
null:x === null - 判断
undefined:x === undefined(或更常见:typeof x === "undefined"在某些边界更稳) - 需要同时覆盖
null/undefined:x == 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同时覆盖两者。