JavaScript null、undefined 與 undeclared 的區別?
2023年8月21日
💎 加入 E+ 成長計畫 與超過 750+ 位工程師一同在社群成長,並獲得更多深度的軟體前後端學習資源
undefined 與 null 的區別 ?
undefined 表示還未定義值,所以當一個變數被宣告但還未被賦予任何值之前,這個變數就會是 undefined,可以理解為「尚未」。
null 代表的是一個變數的空值,可以理解為「沒有」。
undefined 和 null 在 JavaScript 中,都是屬於原始資料類型 (primitive data types) 之一,也就像任何其他資料類別 (data types),例如:string、number一樣,可以被賦予在變數上。兩者在使用上,兩者會有不同的意義。
舉例來說,當前端要向後端索取資料時,因為需要等待資料回傳,所以某個變數一開始可能是 undefined ,當資料回來時,就會變成該資料型態。以下面的例子來說,我們有個變數 users ,定義它的型別為
UserDTO[] | undefined
而不是
UserDTO[] | null
正是因為在拿到資料前, users 是「尚未」。
type UserDTO = {
id: string,
firstName: string,
lastName: string,
profilePicture: string | null,
};
const users: UserDTO[] | undefined = await fetchUsers();
反之亦然,上面的例子中,當拿到了 users ,有些使用者沒有大頭照,因為是「沒有」,所以 profilePicture 的型別是
profilePicture: string | null;
而不是
profilePicture: string | undefined;
undefined 與 undeclared 的區別 ?
undeclared 常會拿來 undefined 做比較,undefined 表示已宣告值是「未定義」,但 undeclared 是指從未被宣告過。
當一個變數並沒有使用 var 、let 或 const 宣告過時,若我們試圖呼叫此變數時,會報 ReferenceError的錯誤。因此在寫程式時,要避免使用 undeclared 的變數。
console.log(x); // Uncaught ReferenceError: x is not defined