JavaScript 的弱型別讓不少行為顯得撲朔迷離,「變數放在 if 裡面算真還是假」就是一例。在強型別語言中,把非 boolean 值放進條件式必須手動轉換;JavaScript 不需要,它會自動做一輪 truthy / falsy 判定。
與其背規則,不如實測一遍:
!function test1() {
var a,
b = -1,
c = 1,
d = 0,
e = null,
f = undefined,
g = '',
h = "",
i = false;
if (!a) { console.log('a=' + a); }
if (!b) { console.log("b=" + b); }
if (!c) { console.log("c=" + c); }
if (!d) { console.log("d=" + d); }
if (!e) { console.log("e=" + e); }
if (!f) { console.log("f=" + f); }
if (!g) { console.log("g=" + g); }
if (!h) { console.log("h=" + h); }
if (!i) { console.log("i=" + i); }
}()
執行結果,被判定為 falsy 的只有這幾個:
a=undefined
d=0
e=null
f=undefined
g=
h=
i=false
而 b(-1)與 c(1)沒有出現,代表它們是 truthy。
全部只有六個值(加上一個特殊情況):
false0(包含 -0 與 0n)""(空字串)nullundefinedNaN除此之外的一切都是 truthy——包含 "0"、"false"、[]、{}、function(){}。這幾個特別容易誤判:空陣列與空物件在條件式中都是真,因為它們是參照型別,只要存在就是真。要判斷空集合,必須另外檢查 arr.length === 0 或 Object.keys(obj).length === 0。
與其依賴自動轉換,不如把條件寫明確,程式碼意圖會清楚很多:
// 較模糊
if (value) { ... }
// 明確表達「不為 null 或 undefined」
if (value != null) { ... }
// 明確表達「不是空字串」
if (value !== '') { ... }
// 明確的布林判斷
if (isEnabled === true) { ... }
另外提醒一個常見 bug:if (someArray) 恆為真,即使它是空陣列。若本意是「有資料才執行」,該寫的是 if (someArray.length > 0)。這類錯誤不會報錯,只會安靜地產生錯誤行為,特別難查。