1、基本使用
空值合并运算符(??)英文名称为 Nullish coalescing operator,是一个逻辑运算符。
特性:当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
2、与逻辑或运算符(||)区别
 
与逻辑或运算符(||)不同的是,当左侧操作数为 0、空字段、布尔false 时,空值合并运算符??均返回左侧操作数。
const num = 0 ?? 1;
console.log(num) // 0const flag = false ?? true;
console.log(flag)  //falseconst str = '' ?? 'string';
console.log(str) // ''
上述场景如果使用 ||,可能会出现不符合预期的结果,因为||是布尔逻辑运算符,左侧操作数会被强制转换为布尔值,任何假值(0, '', NaN, null, undefined)都不会被返回;而空值合并运算符可以有效避免上述问题。
3、??短路逻辑
 
此外,??与 OR 和 AND 逻辑运算符相似,当左表达式不为 null 或 undefined 时,直接返回左侧表达式,不会对右表达式进行求值。
const fn1 = () => {console.log('fn1被调用了'); return 'fn1';}
const fn2 = () => {console.log('fn2被调用了'); return 'fn2';}
const fn3 = () => {console.log('fn3被调用了'); return null;}console.log(fn1() ?? fn2());
//打印 fn1被调用了
// fn1
// 由于fn1 返回值不为null、undefined,fn2 未被调用console.log(fn3() ?? fn2());
//fn3被调用了
//fn2被调用了
//fn2
// 由于fn3 返回值为null,fn2 被调用
4、不能直接与逻辑 &&、||使用
 
要注意的是,由于空值合并运算符??和其他逻辑运算符之间的运算优先级/运算顺序是未定义的,不能直接与逻辑 &&、||使用,否则会抛错;通过括号明确运算优先级,才能正确运行。
true && null ?? 'default string' // 抛出 SyntaxError
false || undefined ?? "default string"; // 抛出 SyntaxError(true && null) ?? "default string"; // true
(false || undefined) ?? "default string"; //'default string'