[week 1]JavaScript中 undefined 與 null 的差異 === 在 Javascript 中,undefined 與 null看起來十分相似,兩者最大的差異在於其代表的意義: * undefined 代表的是未定義,意思便是此變數已經宣告但還未賦值,其值為undefined、類型為undefined * null 代表的則是空值,意思是工程師宣告了這個變數,並強調此變數「無值」(no value),類型為物件(object) 以下我們舉一些例子,並用typeof協助我們了解兩者細微的差異 ## undefined ```javascript= let a; console.log(a); //undefined console.log(typeof undefined) //undefined let b = {name: manson, age:22}; console.log(b.city); //undefined ``` 從上面的例子,我們可以知道: 1. 若變數沒有提供初始值,則預設為undefined值 2. typeof undefined會回傳undefined型別 ## null ```javascript= let a = null; console.log(a); //null console.log(typeof null); //Oject console.log(document.querySelctor('h2')) //null (假設h2元素不存在) ``` 1. 變數宣告為null時,其值為null 2. typeof null會回傳object 3. 在做DOM元素操作時,若要獲取的DOM元素不存在,則會回傳null ## 總結 從以上例子可以得知,undefined與null型別相同但值不同 除了typeof,我們也能利用 == 與 === 來觀察兩者的差異: * null == undefined 回傳true (型別相同) * null === undefined 回傳false (值不同) 需要注意的是,typeof只能區分原始型別( number、string、undefined、boolean、object),因此若使用typeof分辨 null、array、object,皆會回傳object 因此,若要準確地細分,可以使用Object.prototype.toString.call() ## 參考資料 [Javascript中undefined和null的差異](https://snh90100.medium.com/javascript%E4%B8%ADundefined%E5%92%8Cnull%E7%9A%84%E5%B7%AE%E5%88%A5-1f48e9be5e02) [詳解javascript中始資料型別Null和Undefined](https://codertw.com/%e5%89%8d%e7%ab%af%e9%96%8b%e7%99%bc/271856/) [問你喔,null, undefined 和 not defined 是差在哪?](https://karennnnovelty.medium.com/%E3%84%9F%E5%95%8F%E4%BD%A0%E5%96%94-null-undefined-%E5%92%8C-not-defined-%E6%98%AF%E5%B7%AE%E5%9C%A8%E5%93%AA-98204edc07c7)