空值合并运算符

空值合并操作符(??) 是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,''0)时。

 1const x = null ?? 'default string';
 2console.log(x);
 3
 4
 5const y = 0 ?? 15;
 6console.log(y);
 7

使用空值合并操作符

在这个例子中,我们使用空值合并操作符为常量提供默认值,保证常量不为 null 或者 undefined。

 1const nullValue = null;
 2const emptyText = ""; 
 3const someNumber = 15;
 4
 5const x = nullValue ?? "x 的默认值";
 6const y = emptyText ?? "y 的默认值";
 7const z = someNumber ?? 0;
 8
 9console.log(x); 
10console.log(y); 
11console.log(z); 

为变量赋默认值

以前,如果想为一个变量赋默认值,通常的做法是使用逻辑或操作符(||):

 1let x;
 2
 3
 4let someDummyText = x || 'Hi!';

然而,由于 || 是一个布尔逻辑运算符,左侧的操作数会被强制转换成布尔值用于求值。任何假值(0''NaNnullundefined)都不会被返回。这导致如果你使用0''NaN作为有效值,就会出现不可预料的后果。

 1let count = 0;
 2let a = "";
 3
 4let x = count || 15;
 5let y = a || "Hello!";
 6console.log(x);     
 7console.log(y); 

空值合并操作符可以避免这种陷阱,其只在第一个操作数为 nullundefined 时(而不是其它假值)返回第二个操作数:

 1let a = ''; 
 2
 3let x = a || 'Hello world';
 4console.log(x); 
 5
 6let y = a ?? 'Hi!';
 7console.log(y); 

短路

ORAND 逻辑操作符相似,当左表达式不为 nullundefined 时,不会对右表达式进行求值。

 1function A() { console.log('函数 A 被调用了'); return undefined; }
 2function B() { console.log('函数 B 被调用了'); return false; }
 3function C() { console.log('函数 C 被调用了'); return "foo"; }
 4
 5console.log( A() ?? C() );
 6
 7
 8
 9console.log( B() ?? C() );
10
11
12

不能与 AND 或 OR 操作符共用

?? 直接与 AND(&&)OR(||)操作符组合使用是不可取的。应当是因为空值合并操作符和其他逻辑操作符之间的运算优先级/运算顺序是未定义的,这种情况下会抛出 SyntaxError

 1null || undefined ?? "foo"; 
 2true || undefined ?? "foo"; 

但是,如果使用括号来显式表明运算优先级,是没有问题的:

 1(null || undefined ) ?? "foo"; 

与可选链式操作符(?.)的关系

空值合并操作符针对 undefinednull 这两个值,可选链式操作符(?.) 也是如此。在这访问属性可能为 undefinednull 的对象时,可选链式操作符非常有用。

 1let foo = { someFooProp: "hi" };
 2
 3console.log(foo.someFooProp?.toUpperCase()); 
 4console.log(foo.someBarProp?.toUpperCase()); 

判断为' '/null/undefined的用法

 1
 2if((value??'')!==''){
 3
 4}
 5
 6
 7if(value !== null && value !== undefined && value !== ''){
 8
 9}
10
个人笔记记录 2021 ~ 2025