核心誤區
// ❌ 錯誤:若變數未宣告會拋 ReferenceError
if (value === "undefined") { ... }
// ❌ 錯誤:value 可能為 null、0、""、false,皆為 falsy 但非 undefined
if (!value) { ... }
標準寫法:typeof 操作符
// ✅ 正確:不拋錯、精準判斷
if (typeof value === "undefined") {
console.log("value 是 undefined");
}
// typeof 可能回傳值(字串)
// "undefined" | "boolean" | "number" | "string" | "symbol" | "bigint" | "object" | "function"
進階判斷場景
1. 區分 undefined 與 null
let a; // undefined
let b = null; // null
typeof a === "undefined"; // true
typeof b === "undefined"; // false (是 "object")
a === undefined; // true
b === undefined; // false
a == null; // true (鬆散相等:undefined == null)
b == null; // true
a === null; // false
2. 判斷變數是否已宣告
// 全域變數
"myVar" in window; // true/false
// 區域/塊級作用域:僅能用 try-catch 或 typeof
try {
myVar; // 若未宣告拋 ReferenceError
console.log("已宣告");
} catch (e) {
console.log("未宣告");
}
// typeof 不拋錯
typeof myVar === "undefined"; // true (含未宣告、宣告未賦值、賦值 undefined)
3. 物件屬性是否存在
const obj = {a: 1, b: undefined};
"a" in obj; // true
"b" in obj; // true (屬性存在,值為 undefined)
"c" in obj; // false
obj.hasOwnProperty("b"); // true
Object.hasOwn(obj, "b"); // true (ES2022 推薦)
obj.b === undefined; // true,但無法區分「不存在」與「值為 undefined」
4. 函數參數預設值(ES2015+)
function foo(bar = "default") {
// bar 為 undefined 時自動使用預設值
// 若傳入 null,bar 為 null(不觸發預設值)
}
5. 空值合併運算子 ??(ES2020)
const val = userInput ?? "default";
// 僅當 userInput 為 null/undefined 時用預設值
// 0、""、false 會保留原值(優於 ||)
void 0 技巧
// 取得純淨的 undefined(防止被竄改,雖然全域 undefined 唯讀)
const undef = void 0;
value === void 0; // 等同 value === undefined
總結對照表
| 需求 | 推薦寫法 | 備註 |
| 判斷變數值是否為 undefined | typeof val === "undefined" | 最安全、通用 |
| 判斷屬性是否存在(含原型鏈) | "prop" in obj | |
| 判斷屬性是否為自有屬性 | Object.hasOwn(obj, "prop") | ES2022 |
| 判斷值為 null 或 undefined | val == null | 鬆散相等唯一建議用處 |
| 參數/變數預設值 | const x = val ?? "def" | 空值合併 |