很多時候我們會直覺地這樣寫:
if (reValue == undefined) {
alert("undefined");
}
結果發現判斷不出來。查了資料才知道,正確的寫法要用 typeof:
if (typeof (reValue) == "undefined") {
alert("undefined");
}
typeof 回傳的是字串,可能的結果有六種:"number"、"string"、"boolean"、"object"、"function"、"undefined"。
問題不在比較本身,而在於 == 會進行型別轉換,而 undefined 在鬆散相等時等同於 null。於是下面這些都會進入 if 分支:
var reValue = null; reValue == undefined; // true,但你可能只真想攔 undefined
更麻煩的是,如果 reValue 從未用 var/let 宣告過,直接讀取它會丟出 ReferenceError,程式當場中斷:
if (undeclaredVar == undefined) { } // ReferenceError!
因為 typeof 是運算子而非函式,對未宣告的識別字不會拋錯,只會回傳字串 "undefined"。這正是它成為經典寫法的原因。
如果你確定變數已經宣告過,=== 更直接也更嚴格:
if (reValue === undefined) { }
若同時想排除 null(實務上很常見),有個簡潔的慣用寫法:
if (reValue == null) { } // 同時涵蓋 null 與 undefined
這可以說是 == 少數真正好用而無歧義的場合,值得記住。
而 ES2020 之後,很多原本需要判斷 undefined 的場景,都有更好的工具可用:
const port = config.port ?? 3000; // 只在 null/undefined 時取預設
const city = user?.address?.city; // 鏈上任一環為空即回傳 undefined
const { a = 1 } = options; // 解構賦值預設值
結論:typeof x === "undefined" 是處理「變數可能未宣告」的正解;x === undefined 適合已宣告的變數;而要連 null 一起攔下,用 x == null。三者的適用情境不同,選對了就不會再出現「判斷不出來」的困惑。