JavaScript语法特性篇-空值合并运算符(??)

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) // 0

const flag = false ?? true;
console.log(flag)  //false

const str = '' ?? 'string';
console.log(str) // ''

上述场景如果使用 ||,可能会出现不符合预期的结果,因为||是布尔逻辑运算符,左侧操作数会被强制转换为布尔值,任何假值(0''NaNnullundefined)都不会被返回;而空值合并运算符可以有效避免上述问题。

3、??短路逻辑

此外,??与 OR 和 AND 逻辑运算符相似,当左表达式不为 nullundefined 时,直接返回左侧表达式,不会对右表达式进行求值。

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'
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端后花园

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值