在布尔上下文中(if、&&、||、!),每个值都会被当作 真值(truthy) 或 假值(falsy) 来处理。一共有 8 个假值 —— 其余所有值都是真值。
假值包括:false、0、-0、0n(BigInt 零)、""(空字符串)、null、undefined、NaN。
js
if ("") {} // skipped — empty string is falsy
if (0) {} // skipped
if ("0") {} // RUNS — non-empty string is truthy!
if ([]) {} // RUNS — empty array is truthy!
if ({}) {} // RUNS — empty object is truthy!
容易让人意外的是:"0"、[] 和 {} 全都是 真值,尽管它们看起来“空空如也”。
一个常见的真实 bug
js
const name = input || "guest"; // ❌ if input is "" or 0, falls back to "guest"
const count = input ?? 0; // ✅ ?? only falls back on null/undefined
|| 会对 任何 假值进行回退,所以一个有效的 0 或 "" 也会被替换掉。而 空值合并(nullish coalescing) 运算符 ?? 只 在值为 null/undefined 时才回退,这通常才是你真正想要的行为。
为什么这很重要
清楚地掌握这套假值集合可以避免一些隐蔽的 bug —— 尤其是在判断数字时(应写 if (count > 0) 而非 if (count)),以及在设置默认值时选择 ?? 还是 ||。
