js中null 跟undefine的区别(JavaScript 精华笔记)
在 JavaScript 中,null 和 undefined 都表示“没有值”或“空”,但它们有不同的含义和使用场景。下面是详细区别:
✅ 基本区别
| 特性 | undefined |
null |
|---|---|---|
| 含义 | 变量已声明但未赋值 | 变量已赋值为空值 |
| 类型 | undefined 类型 |
object 类型(这是历史遗留问题) |
| 谁设置的 | JavaScript 引擎自动赋值 | 开发者手动赋值 |
| 用法场景 | 表示“未定义” | 表示“有意为空” |
🔹 示例对比
let a;
console.log(a); // undefined:声明了但没赋值
let b = null;
console.log(b); // null:明确赋值为空
🔸 使用场景
undefined 常见于:
- 变量声明但未赋值
- 函数没有
return值时 - 访问对象中不存在的属性
let x;
console.log(x); // undefined
function test() {}
console.log(test()); // undefined
let obj = {};
console.log(obj.noSuchProp); // undefined
null 常见于:
- 主动赋值为“无值”
- 初始化对象或变量,表示将来可能赋值
- 与 DOM 操作有关的场景(如
getElementById找不到元素时返回 null)
let user = null; // 表示当前用户为空
let el = document.getElementById('no-id');
console.log(el); // null
⚠️ 类型比较
null == undefined // true(值相等,类型不同,非严格比较)
null === undefined // false(严格比较,类型和值都要一致)
typeof undefined // "undefined"
typeof null // "object"(历史遗留 bug)
✅ 总结记忆
- undefined:变量还没准备好(系统默认)
- null:我已经准备好了,但故意空着(开发者手动)
在代码中,如果需要设置“无值”状态,推荐统一用 null 表示“我知道这里空是有意义的”。而 undefined 更适合检测异常或错误情况。

浙公网安备 33010602011771号