undefined和null的区别

undefined和null的区别

js 最初设计的缺陷导致 js 神奇的存在两个空值: undefinednull
其他语言中有且只有 null , NULL 等。

实际开发中,将一个变量赋值为 undefinednull 几乎没有区别,且两者都为 Falsy

那么两者的区别到底是什么呢?

区别

定义上的区别

MDN 的解释:

null 是一个字面量,不像 undefined ,它不是全局对象的一个属性。null 是表示缺少的标识,指示变量未指向任何对象。把 null 作为尚未创建的对象,也许更好理解。在 API 中,null 常在返回类型应是一个对象,但没有关联的值的地方使用。

undefined 是全局对象的一个属性。也就是说,它是全局作用域的一个变量。undefined 的最初值就是原始数据类型 undefined。

我的理解是: undefined 表示未初始化。 null 表示已经初始化,但是没有指向任何对象。

一张经典的图帮助理解:

区别

表现上的区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
typeof undefined; // 'undefined'
typeof null; // 'object'

Object.prototype.toString.call(null); // '[object Null]'
Object.prototype.toString.call(undefined); // '[object Undefined]'

null == undefined; // true
null === undefined; // false
!!null === !!undefined; // true

undefined + 0; // NaN
null + 0; // 0

// 在JSON.stringify()时,值为undefined的属性会被忽略
JSON.stringify({
a: undefined,
b: null
}); // '{b: null}'

ref

  1. https://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html
  2. https://mp.weixin.qq.com/s/N43cy14qN5FkomwhGbuxAw

评论