[JS] undefined 和 null 的差異


Posted by Genos on 2021-11-17

undefined 是 JavaScript 的特有物之一,新手入門時,常會對 undefined 和 null 這兩個型別產生疑問,下面就來逐步解說。

💎 null

null 表示一個空值,是各種程式語言中常見的型別。

如果有後端、資料庫類的學習經驗,在 SQL 資料庫設計資料表時,會有一些欄位是非必要填寫,但是新增資料時所有的欄位都需要放入資料,這時候就可以在非必要欄位設定『允許 null』,當資料建立起來的時候,這些沒填的欄位就會塞入 null 來表示空值。

JavaScript 中的 null 是一種原始型別,可以賦予變數的值為 null 來表示他是空值,這是合法的操作,不會有任何錯誤。

let a = null; // 不要包引號,會變成字串
console.log(a); // null

除此之外,null 還有一些特色:

  1. 檢查型別(typeof)的萬年 bug(因影響甚遠,此錯誤不會修正),正確是 null。
    console.log(typeof null); // object
    
  2. null 雖然代表著空值,但是轉型成字串時會是字面上的英文。
    console.log(null + ''); // 'null'
    

參考資料:
MDN-null
MDN-typeof

💎 undefined

undefined 從字面上可以理解成『未定義』,表示這個變數並沒有被賦予任何的值,跟已經被賦予空值(null)代表著不一樣的資料狀態,比起 null,undefined 更容易跟 not defined 搞混:

  • undefined 是變數已被宣告未賦值,屬於原始型別之一。
  • not defined 是變數未被宣告,不屬於原始型別,是程式執行時的錯誤訊息(runtime error)
    let a;
    console.log(a); // undefined
    console.log(typeof a); // undefined
    console.log(b); // ReferenceError: b is not defined
    console.log(typeof b); // undefined
    

💎 null == undefined ?

看完前面的段落,可以知道 undefined 和 null 意義上是完全不同,接著來比較看看:

console.log(undefined == null); // true

奇怪了,不是說好不一樣的嗎?
可能是轉型在作亂,改用嚴格比較(===)看看。

console.log(undefined === null); // false

果然是轉型搞的鬼,但是為什麼 undefined 和 null 轉型後會相等?下個段落接續說明。

💎 truthy & falsy

JavaScript 中的各種值都可以被轉換成布林值(Boolean),轉換後為 true 的值稱為 truthy,反之則稱為 falsy,除了以下所列的值屬於 falsy 值,其他都是 truthy 值。
(完整的圖表可以參考 JS Comparison Table

  • false
  • 0
  • -0
  • 0n (BigInt)
  • "" (空字串,包含 單引號反引號)
  • null
  • undefined
  • NaN
  • document.all (正常不會用到)

由上可知,nullundefined都是falsy值,在做一般相等的比較時,都會被轉成 false,所以得到的結果是 true。

truthy 和 falsy 的運用:檢查資料是否存在時可以運用轉成布林值的方法減少程式碼撰寫長度。

  • 原始寫法:if (arr[0] === undefined) {...}
  • 轉型為布林值:if (!arr[0]) {...}

參考資料:
MDN-Falsy
dorey-JS Comparison Table

💎 null 和 undefined 出現時機

除了未賦值的 undefined 和自己定義的 null 外,還有什麼時候會出現呢?

  • null: 會出現在 BOM(Browser Object Model)中不存在的資料,例如:document.querySelector、localStorage、 sessionStorage...等,不存在時會得到 null。
    localStorage.getItem('a'); // null
    sessionStorage.getItem('a'); // null
    
  • undefined: 取用不存在 JS 檔案中未賦值的資料會得到 undefined。
    let arr = [];
    let obj = {};
    console.log(arr[1]); // undefined
    console.log(obj.a); // undefined
    

以上是我對這兩個型別的一點認知,如有錯誤或是補充的知識點,也歡迎大家不吝指教,謝謝!


#javascript







Related Posts

【JS基礎】字串處理

【JS基礎】字串處理

邏輯論證(Logical Argument)

邏輯論證(Logical Argument)

Day 23-Turtle Crossing Game

Day 23-Turtle Crossing Game


Comments