| 代碼 | 結果 | 類型 |
|---|---|---|
console.log(a) (未聲明) | ReferenceError: a is not defined | 拋出異常,代碼中斷 |
var a; console.log(a) | undefined | 正常返回 undefined |
var b={}; console.log(b.a) | undefined | 屬性不存在,返回 undefined |
function C(){}; new C().a | undefined | 實例屬性不存在 |
typeof a; // "undefined" — 不拋錯,typeof 安全檢測未聲明變量
typeof undeclaredVar; // "undefined"
typeof 是唯一能安全檢測未聲明變量的操作符。
var d = a || 3; // ReferenceError: a not defined — 短路求值前需先讀取 a
var a;
var d = a || 3; // 3 — a 為 undefined(falsy),返回 3
22 || 44; // 22 — 短路,返回第一個 truthy
false || 33; // 33
核心規則:|| 返回第一個 truthy 值,或最後一個值。讀取未聲明變量直接拋錯,不進入短路邏輯。
if (x) { } // ReferenceError: x not defined
var x;
if (x) { } // 不執行,undefined 為 falsy
ReferenceErrorundefined → "不明確的、未確定的"(存在但無確定值)not defined → "未定義的"(根本不存在)// 安全檢測未聲明/undefined
if (typeof someVar !== 'undefined') { ... }
// 或 ES2022: Object.hasOwn(window, 'someVar') // 僅檢測全局屬性
// 默認值賦值
const value = someVar ?? 'default'; // nullish coalescing,僅 null/undefined 時生效