null和undefined

nul和undefined都表示”没有”,语法效果几乎没有区别

1
2
3
var a = undefined;
// 或者
var a = null;

上面两种写法几乎等价

在if语句中,他们都会自动转为false,判断相等运算符(==)报告两者相等

1
2
3
4
5
6
7
8
9
10
11
12
if (!undefined) {
console.log('undefined is false');
}
// undefined is false

if (!null) {
console.log('null is false');
}
// null is false

undefined == null
// true

null和undefined数据类型不一样

1
2
typeof(null);  //object
typeof(undefined); //undefined

null和undefined转为数字时不一样

1
2
3
4
5
Number(null) // 0
5 + null // 5

Number(undefined) // NaN
5 + undefined // NaN