null和undefined有相同點墩剖,也有不同的地方俄占,總結下異同點如下:
相同點
-
Undefined類型衍生自Null類型恐疲,因此在使用相等比較符判斷時會返回true
console.log(null == undefined); // true
-
null和undefined在if條件或while循環(huán)語句中都會被轉換為false添诉,使用Boolean()轉型函數(shù)同樣都會被轉換為false挑社。
console.log(Boolean(null)); // false console.log(Boolean(undefined)); // false
Null類型和Undefined類型都只有一個值
-
null和undefined都沒有對應的包裝對象,因此在這兩個類型上調用屬性和方法時都會拋出異常顿痪。
let a = null; let b; console.log(a.name); // Uncaught TypeError: Cannot read property 'name' of null console.log(b.name); // Uncaught TypeError: Cannot read property 'name' of undefined
不同點
-
Null類型和Undefined類型是兩種不同的基本類型镊辕,因此使用typeof操作符檢測時會返回不同的值。
console.log(typeof null); // 'object' console.log(typeof undefined); // 'undefined'
因此使用全等操作符進行判斷時會返回false蚁袭。
console.log(null === undefined); // false
需要進行字符串類型的轉換時征懈,null會轉換成'null',undefined會轉換成'undefined'揩悄。
-
轉換成數(shù)字類型時卖哎,null會轉換成0,而undefined則會轉換成NaN删性。
console.log(Number(null)); // 0 console.log(Number(undefined)); // NaN
沒必要給變量顯式賦值為undefined亏娜,而當我們定義一個變量想要以后保存對象時,可以賦值null蹬挺。