The difference between a variable: null, undefined or undeclared
null 變數存在被賦予空、未知的值
undefined 變數存在但還沒有被賦值
undeclared 變數不存在
(同場加映)NaN 非數值的數值
-
null:
- 表示不存在任何對象值
- 通常在可以預期對象但沒有相關對象的地方檢索。
- 作為物件原型鏈的終點。
- 布林值的判斷為 false
- 屬性為object(它不是全域對象的屬性標識符, 是用文字寫入的null)
-
undefined:
-
變數被聲明了,但沒有賦值時,就等於undefined,如下圖:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
-
呼叫函式時,應該提供的引數沒有提供,該引數等於undefined,如下圖:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
-
物件沒有賦值的屬性,該屬性的值為undefined,如下圖:
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
-
函式沒有返回值時,預設返回undefined。
-
布林值判斷為false
- 屬性為undefined(全域属性,屬性即為undefined)
-
undeclared:
- 指js的語法錯誤,會顯示ReferenceError,指沒有申明直接使用,導致js無法找到對應的上下文。
- 變數在未宣告並使用的狀況下會得到 ReferenceError,並指出該變數並未宣告。
-
NaN (同場加映)
- NaN 是 "Not a Number" 的簡稱,數學計算中,若無法產生數值時或程式無法表示值時,就會是NaN。
- 布林值判斷為false
How would you go about checking for any of these states?
你如何檢查?
參考資料
MDN: null
MDN: undefined
MDN: NaN
小雕雕的家: Javascript 基礎打底系列 (二) - null、undefined、NaN 的差異與檢查方式
Summer。桑莫。夏天: 你懂 JavaScript 嗎?#4 型別(Types)
Elaine's Blog: JavaScript null、undefined 與 undeclared
itread01: null,undefined,undeclared的區別Script