??(空值合并运算符)和 ||(逻辑或运算符)都用于提供默认值,但它们在判断“何时使用默认值”的标准上完全不同:
区别
a ?? b:仅当a是null,undefined时,才使用b。a || b:当a是任意“假值”(false, 0, -0, 0n, '', null, undefined, NaN)时,就使用b。
对比表:不同值的表现
| 表达式 | 结果 | 说明 |
|---|---|---|
null ?? [] | [] | null 触发默认值 |
undefined ?? [] | [] | undefined 触发默认值 |
0 ?? [] | 0 | ✅ 0 是有效值,不触发默认值 |
'' ?? {} | '' | ✅ 空字符串是有效值,不触发默认值 |
false ?? {} | false | ✅ false 是有效值,不触发默认值 |
null || [] | [] | null 是假值,触发默认值 |
0 || [] | [] | ❌ 0 是假值,触发默认值 |
'' || {} | {} | ❌ 空字符串是假值,触发默认值 |
false || {} | {} | ❌ false 是假值,触发默认值 |
实际场景举例
场景 1:数组兜底
const arr = getArray(); // 可能返回 null / undefined / []
const safeArr = arr ?? []; // 只有 null/undefined 才兜底
场景 2:对象兜底
const config = userConfig ?? defaultConfig; // 仅 null/undefined 兜底
场景 3:数字 0 是合法值
const height = 0;
console.log(height ?? 100); // 0(正确保留)
console.log(height || 100); // 100(错误被替换)
总结建议
| 使用场景 | 推荐 |
|---|---|
只想排除 null 和 undefined | ✅ ?? |
| 想排除所有假值(如 0、''、false) | ✅ || |
一句话:
??更严格,只关心“有没有值”;||更宽松,只要“值不真”就替换。