null和undefined的区别

null 和 undefined 是 JavaScript 中两个特殊的值,它们都表示“无”或“空”,但在语义和使用场景上有明显区别。以下是它们的详细对比:


1. 定义

  • undefined

    • 表示变量已声明但未赋值,或函数没有返回值时的默认返回值。

    • 是 JavaScript 引擎默认赋予的初始值。

    • 类型为 undefined

  • null

    • 表示一个空对象指针,通常用于显式表示“无”或“空”。

    • 是开发者主动赋值的值。

    • 类型为 object(这是 JavaScript 的历史遗留问题)。


2. 使用场景

  • undefined

    • 变量声明但未初始化时。

    • 函数参数未传递时。

    • 函数没有返回值时。

    • 访问对象不存在的属性时。

  • null

    • 显式表示一个空值或无效值。

    • 用于初始化变量,表示该变量未来会被赋值为对象。

    • 用于释放对象引用(如 obj = null)。


3. 示例

let a;          // 声明但未赋值
console.log(a); // undefined

function foo(b) {
  console.log(b); // 参数未传递时为 undefined
}
foo();

let obj = { name: 'Alice' };
console.log(obj.age); // 访问不存在的属性,返回 undefined

let c = null; // 显式赋值为 null
console.log(c); // null

4. 类型检查

  • typeof 结果

    • undefined 的类型是 undefined

    • null 的类型是 object(历史遗留问题)。

console.log(typeof undefined); // 'undefined'
console.log(typeof null);      // 'object'
  • 相等性检查

    • == 会认为 null 和 undefined 相等(null == undefined 为 true)。

    • === 会严格区分 null 和 undefinednull === undefined 为 false)。

console.log(null == undefined);  // true
console.log(null === undefined); // false

5. 默认值处理

  • undefined

    • 在默认值赋值(如 let a = undefined ?? 'default')中,undefined 会被覆盖。

    • 在函数参数默认值中,undefined 会触发默认值赋值。

  • null

    • 在默认值赋值中,null 不会被覆盖(如 let a = null ?? 'default' 返回 'default')。

    • 在函数参数默认值中,null 不会触发默认值赋值。

function greet(name = 'Anonymous') {
  console.log(`Hello, ${name}!`);
}

greet(undefined); // Hello, Anonymous!
greet(null);      // Hello, null!

6. JSON 序列化

  • undefined

    • 在 JSON 序列化时会被忽略(不会出现在结果中)。

  • null

    • 在 JSON 序列化时会被保留。

const obj = { a: undefined, b: null };
console.log(JSON.stringify(obj)); // '{"b":null}'

7. 总结对比

特性 undefined null
含义 未定义或未赋值 显式表示空值或无效值
类型 undefined object(历史遗留问题)
默认值处理 触发默认值赋值 不触发默认值赋值
JSON 序列化 被忽略 被保留
使用场景 变量未初始化、函数无返回值等 显式表示空值、释放对象引用等

8. 最佳实践

  1. undefined

    • 用于表示变量未初始化或函数无返回值。

    • 避免显式赋值 undefined,应让 JavaScript 引擎自动处理。

  2. null

    • 用于显式表示空值或无效值。

    • 在需要释放对象引用时使用(如 obj = null)。

  3. 检查空值

    • 使用 == 检查 null 或 undefinedif (value == null)

    • 使用 === 严格区分 null 和 undefined

if (value == null) {
  // 同时检查 null 和 undefined
}

if (value === null) {
  // 仅检查 null
}

if (value === undefined) {
  // 仅检查 undefined
}