JavaScript 中 null 和 undefined 的区别及使用场景
1. 为什么存在 null 和 undefined
在 JavaScript 中,null 和 undefined 是为了表示两种不同概念:
undefined:表示变量已声明,但尚未赋值。
null:表示变量已赋值,但特意赋为 “空值”。
2. 区别详解
(1) 语义
undefined:表示变量已声明,但尚未初始化。
null:表示变量有意被赋值为空,通常用于表示对象引用的“空状态”。
(2) 类型
undefined 是原始值,属于 undefined 类型。
null 是原始值,属于 object 类型(这是一个历史遗留问题)。
1 2
| console.log(typeof undefined); console.log(typeof null);
|
(3) 比较
松散比较 ==:null==undefined为true,这是一个强制规定
严格比较 ===: null==undefined为false,因为类型不同
1 2
| console.log(null == undefined); console.log(null === undefined);
|
3. 使用场景
(1) 使用 undefined
undefined 通常由 JavaScript 自动分配,不需要显式赋值:
- 表示变量 “未被赋值”。
- 表示对象属性不存在。
- 表示函数参数未传递。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| let a; console.log(a);
let obj = {}; console.log(obj.value);
function test(param) { console.log(param); }
test();
|
(2) 使用 null
null 需要开发者主动赋值,用于表示 “空值” 或 “空对象”:
- 初始化一个变量,表示未来会赋值。
- 表示资源尚未分配或不需要时显式清空。
1 2 3 4 5 6 7 8 9
| let data = null; console.log(data);
let person = null; if (isDataReady()) { person = {name: "John"}; }
|
4. 默认值为 undefined
如果声明了变量但没有赋值,它的默认值为 undefined: