ES6 null coalescing operator (??)

Article directory

Null coalescing operator (??)

When we get data from the backend interface, we often encounter the situation that the backend lacks fields, so the frontend has to do null value compatibility to prevent the backend from not giving fields

For example, when we need to obtain product prices, we will write:

const price = res.data?.price || '暂无标价'

But in fact, this approach is problematic. Obviously, if the price of a free product is 0, our || here will generate a bug. And when you are used to the || writing method, it is easy to ignore this potential problem. When the bug occurs, we can only change it to:

const price = (res.data?.price === null || res.data?.price === undefined) ? '暂无标价' : res.data?.price 

Obviously this code is long and poorly readable. Is there a better way to judge whether a field is empty? Yes, that is the null value coalescing operator??.

const price = res.data?.price ?? '暂无标价' 

The code suddenly becomes more streamlined and more comfortable!
As you can see, the null coalescing operator (??) is a logical operator that returns its right operand when the left operand is null or undefined, otherwise returns the left operand.
In some business scenarios, || can be used instead of || to avoid using || to set default values ​​for some variables, which may encounter unexpected behavior. (eg, ' ' or 0)

const res={
    
    data:{
    
    price:0}}
const price=res.data?.price??'123'
console.log(price)
 0

Normally written judgments tend to ignore 0 and empty strings' '
insert image description here

Use ?? to accurately judge
insert image description here

Guess you like

Origin blog.csdn.net/weixin_53125679/article/details/125500642