|| 和 ?? 的核心差异(JavaScript / Node.js)
1. ||(逻辑或 / Logical OR)
- 只要左边的值是 falsy(假值),就返回右边的值。
- Falsy 值包括:false、0、''(空字符串)、null、undefined、NaN。
const a = 0 || '默认值'; // → '默认值'(因为 0 是 falsy)
const b = '' || '默认值'; // → '默认值'
const c = null || '默认值'; // → '默认值'
const d = undefined || '默认值'; // → '默认值'
const e = 'hello' || '默认值'; // → 'hello'
2. ??(空值合并 / Nullish Coalescing)
- 只有左边是 null 或 undefined 时,才返回右边的值。
- 其他 falsy 值(0、''、false、NaN)都会被保留。
const a = 0 ?? '默认值'; // → 0(保留 0)
const b = '' ?? '默认值'; // → ''(保留空字符串)
const c = null ?? '默认值'; // → '默认值'
const d = undefined ?? '默认值'; // → '默认值'
const e = 'hello' ?? '默认值'; // → 'hello'
const f = false ?? '默认值'; // → false
对比总结
| 左边的值 | || 结果 | ?? 结果 | |--------------|---------------|---------------| | 0 | 取右边 | 保留 0 | | '' | 取右边 | 保留 '' | | false | 取右边 | 保留 false| | null | 取右边 | 取右边 | | undefined | 取右边 | 取右边 | | 有意义的值 | 保留左边 | 保留左边 |
实际使用建议
- 需要把 0、空字符串、false 也当成“有效值”时 → 用 ??
- 只想在值为空(null/undefined)时才给默认值 → 用 ??(更推荐)
- 想把所有 falsy 值都替换成默认值 → 用 ||
// 常见场景:配置项默认值
const port = process.env.PORT ?? 3000; // 推荐,允许端口为 0
const name = user.name || '匿名用户'; // 空字符串也会变成默认值