null 與 undefined 的差別
undefined是基本型別之一,指的是「變數目前還沒有給值」,如果宣告一個變數,卻沒有初始化(沒有給值),那變數的值就預設為undefined。
let a;
console.log(a)//undefined
Number(undefined); //NaN
console.log(1+undefined); //NaN
typeof(undefined); //'undefined'
Boolean(undefined);//false,在求布林值時會轉成false
null也是基本型別之一,指的是「不管前500年,還是後500年有沒有值,總之現在沒有值」。
在指定DOM元素時,如果那個DOM元素不存在,也會回傳null。
let b = null;
console.log(b);//null
Number(null) //0
console.log(1+null); //0,1 + 0 =1
typeof(null) //'object'
Boolean(null) //false,在求布林值時會轉成false
但是要注意的是:
null == undefined; //true,因為在JS中用布林去查詢null跟undefined都是falsy
null === undefined; //false
最後的重點整理:
undefined和null相似處:
- 都没有屬性和方法,也不能額外添加屬性方法
- 皆為Falsy Value(Boolean判斷時為false)
- 皆為原始型別(Primitive Type)
undefined和null相異之處:
typeof null
會回傳 object ;typeof undefined
會回傳 undefined。- 當要取用一個物件的屬性或陣列的元素時,若該屬性/元素不存在,回傳undefined。或原本一個函數需要傳入參數,但是調用函數時卻沒有傳入參數,則回傳值將會是undefined。
- 在做DOM元素操作時,若要獲取的DOM元素不存在,則會回傳null。
參考資料
null 與 undefined 的差別
https://popeye-ux.github.io/2021/10/23/nullUndefined/