null和undefined有什么区别

124 阅读2分钟

在 JavaScript 中,null 和 undefined 都表示“空值”或“不存在”,但它们在语义和用法上有重要区别:

1. 语义上的区别

  • undefined:表示“变量已声明但未赋值”
    • 系统自动赋予的默认值
    • 表示“缺少值”,即应该有值但还没有定义
  • null:表示“变量已赋值,但值为空”
    • 程序员主动赋予的空值
    • 表示“有值,但值为空对象”

2. 类型区别

typeof undefined    // "undefined"
typeof null         // "object" (历史遗留问题,实际应为"null")

3. 相等性比较

// 宽松相等(==)
null == undefined    // true
null == null         // true
undefined == undefined // true

// 严格相等(===)
null === undefined   // false
null === null        // true
undefined === undefined // true

4. 常见出现场景

undefined 出现的情况:

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

let obj = {};
console.log(obj.x);   // 访问不存在的属性

function foo(x) {
    console.log(x);
}
foo();               // 函数参数未传递

function bar() {
    // 没有return语句
}
let result = bar();  // 函数没有返回值

let arr = [1, 2];
console.log(arr[5]); // 数组越界访问

null 出现的情况:

// 主动赋值为空
let a = null;

// DOM操作
document.getElementById('不存在的id'); // 返回null

// 表示空对象引用
let obj = null;

// 作为函数的返回值,表示空值
function findUser(id) {
    if (!exists(id)) {
        return null; // 明确表示"没找到"
    }
    return {id, name: "John"};
}

5. 数值转换

Number(undefined)   // NaN
Number(null)        // 0

1 + undefined       // NaN
1 + null            // 1

6. 最佳实践

使用建议:

  • 用 undefined 表示
    • 变量未初始化
    • 函数参数未提供
    • 对象属性不存在
  • 用 null 表示
    • 主动清空对象引用
    • 明确表示“空值”或“无对象”

检查方法:

// 检查是否为 null
value === null

// 检查是否为 undefined
value === undefined
typeof value === 'undefined'

// 检查是否为 null 或 undefined(推荐)
value == null  // true for null AND undefined
value == undefined

// ES6+ 更好的方式
value === null || value === undefined

// 或使用默认值
let value = someValue ?? 'default';

7. JSON 中的区别

JSON.stringify({a: undefined, b: null})
// 结果: '{"b":null}' (undefined会被忽略)

总结对比表

特性undefinednull
类型"undefined""object"
含义未定义/缺失值空对象引用
来源系统自动赋值程序员主动赋值
数值转换NaN0
JSON序列化被忽略保留
相等性undefined == null (true)null == undefined (true)

简单记忆undefined 是系统告诉你“还没赋值”,null 是你告诉系统“这个值就是空的”。