空值合并操作符( ??
)是一个逻辑操作符,当左侧的操作数为 null
或者 undefined
时,返回其右侧操作数,否则返回左侧操作数。
const foo = null ?? 'default value';
// foo -> 'default value'
const bar = undefined ?? 'default value';
// bar -> 'default value'
const foo1 = false ?? 'false value';
// foo1 -> false
const bar1 = 0 ?? 'zero value';
// bar1 -> 0
逻辑或操作符( ||
)会在左侧操作数为假值时返回右侧操作数。
然而,由于 ||
是一个布尔逻辑运算符,左侧的操作数会被强制转换成布尔值用于求值。任何假值(0
, ''
, NaN
, null
, undefined
)都不会被返回。这导致如果你使用0
,''
或NaN
作为有效值,就会出现不可预料的后果。
let count = 0;
let text = "";
let qty = count || 42;
let message = text || "hi!";
console.log(qty); // 42,而不是 0
console.log(message); // "hi!",而不是 ""
空值合并操作符可以避免这种陷阱,其只在第一个操作数为null
或 undefined
时(而不是其它假值)返回第二个操作数:
let myText = ''; // An empty string (which is also a falsy value)
let notFalsyText = myText || 'Hello world';
console.log(notFalsyText); // Hello world
let preservingFalsy = myText ?? 'Hi neighborhood';
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
短路
与 OR 和 AND 逻辑操作符相似,当左表达式不为 null
或 undefined
时,不会对右表达式进行求值。
也就是说,当左侧表达式为null
或undefined
时,才会对右侧求值
function A() { console.log('函数 A 被调用了'); return undefined; }
function B() { console.log('函数 B 被调用了'); return false; }
function C() { console.log('函数 C 被调用了'); return "foo"; }
console.log( A() ?? C() );
// 依次打印 "函数 A 被调用了"、"函数 C 被调用了"、"foo"
// A() 返回了 undefined,所以操作符两边的表达式都被执行了
console.log( B() ?? C() );
// 依次打印 "函数 B 被调用了"、"false"
// B() 返回了 false(既不是 null 也不是 undefined)
// 所以右侧表达式没有被执行