JavaScript's ?? and ?.

The explanation on the Internet is a bit too complicated. Here is a simple example to describe it.
??
const nowTime = newTime ? newTime : oldTime
const nowTime = newTime ?? oldTime

These two sentences have the same meaning. In fact, they are the abbreviation used when the variables on both sides are the same.

?.
const time = item ? item.time : undefined
const time = item?.time

These two sentences also mean the same thing, that is?. No error will be reported when the value on the left is empty.

Anyone familiar with JavaScript knows that when a value is null or undefined and then accessing its properties, an error will be reported. Therefore, when we perform the following operations, we generally use ternary or if to judge and then assign the value.

const time = item.time

But when we use ?., if item is equal to null or undefined, then the value of time will be undefined and no error will be reported.

Supongo que te gusta

Origin blog.csdn.net/weixin_45772041/article/details/129662852
Recomendado
Clasificación