空值合并运算符( ?? )是一个逻辑运算符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
与逻辑或运算符(||)不同,逻辑或运算符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,'' 或 0)时。见下面的例子。
function demo() {
console.log("undefined ?? 'default string'output======>", undefined ?? 'default string'); // output: "default string"
console.log("null ?? 'default string'output======>",null ?? 'default string'); // output: "default string"
console.log("0 ?? 42 output======>", 0 ?? 42); // output 0
console.log("false ?? true output======>", false ?? true); // output false
console.log("'' ?? '123' output======>", '' ?? '123'); // output ''
}
使用场景:
1. 变量赋默认值
保证常量不为 `null` 或者 `undefined`
const nullValue = null;
const emptyText = ""; // 空字符串,是一个假值,Boolean("") === false
const someNumber = 42;
const valA = nullValue ?? "valA 的默认值";
const valB = emptyText ?? "valB 的默认值";
const valC = someNumber ?? 0;
console.log(valA); // "valA 的默认值"
console.log(valB); // ""(空字符串虽然是假值,但不是 null 或者 undefined)
console.log(valC); // 42
与逻辑运算符 || 的区别
如果想为一个变量赋默认值,通常的做法是使用逻辑或运算符(||):
let foo; // undefined
let text = foo || 'Hello!';
console.log("output======>",text); // output 'Hello'
由于 || 是一个布尔逻辑运算符,左侧的操作数会被强制转换成布尔值用于求值。任何假值(0, '', NaN, null, undefined)都不会被返回
空值合并运算符可以避免这种陷阱,其只在第一个操作数为null 或 undefined 时(而不是其它假值)返回第二个操作数:
let text = ''; // 空字符串
let textA = text || 'Hello world';
console.log(textA); // Hello world
let textB = text ?? 'Hello world';
console.log(textB); // '' (text不等于`null`, `undefined`返回右侧的值 )
总结:
- 空值合并运算符
??提供了一种从列表中选择第一个“已定义的”值的简便方式。 - 它被用于为变量分配默认值:
// 当 text 的值为 null 或 undefined 时,将 text 的值设置为 100
text = text ?? 100;
-
??运算符的优先级非常低,仅略高于?和=,因此在表达式中使用它时请考虑添加括号。 -
如果没有明确添加括号,不能将其与
||或&&一起使用。