简体   繁体   English

?? 和 ||

[英]Difference between ?? and ||

I was going through the new proposed functionalities in ES2020 and I stumbled upon the ??我正在浏览 ES2020 中提出的新功能时,偶然发现了 ?? operator also known as the “nullish coalescing operator”.运算符也称为“空合并运算符”。

The explanation was vague and I still don't get how it is different from the logical OR operator ( || )解释很模糊,我仍然不明白它与逻辑 OR 运算符( || )有何不同

Explanation is very simple lets assume that we have next situation, we want to get a value if it exist in object or use other value if it's undefined or null解释很简单让我们假设我们有下一种情况,如果它存在于对象中,我们想要获取一个值,或者如果它未定义或为空,则使用其他值

const obj = { a: 0 }; 
const a = obj.a || 10; // gives us 10

// if we will use ?? operator situation will be different
const obj = { a: 0 };
const a = obj.a ?? 10; // gives us 0

// you can achieve this using this way
const obj = { a: 0 };
const a = obj.a === undefined ? 10 : obj.a; // gives us 0

// it also work in case of null
const obj = { a: 0, b: null };
const b = obj.b ?? 10; // gives us 10

Basically this operator does next:基本上这个操作符接下来会做:

// I assume that we have value and different_value variables
const a = (value === null || value === undefined) ? different_value : value;

More information about this you can find in MDN web docs您可以在MDN 网络文档中找到有关此的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM