The ? optional chaining operator and the difference between ?? and ||

? optional chaining operator

? It is an optional chain operator . It is often used when accessing internal data with uncertain reference types . For example, to access an array in an object, you can use it if you are not sure that the array must have data? Read its length property, if the object Without this attribute, it will only return undefined without reporting an error, which can effectively avoid the error of "there is no length attribute on undefined"!

Code example:

let data = {name: 'zs'}
console.log(data.list.length)        // 代码会报错!!!!

let data = {name: 'zs'}
console.log(data.list?.length)       // 返回 undefined 而不会报错

?? and ||

Both the ?? and || operators can be used in the case of setting a "default/alternate value" , but they have a slight difference:

The ?? operator will only take the value on the right when the data on the left is undefined or null , so when the data on the left is 0 / false, it will not take the data on the right , and still take the 0 / false on the left

Code example:

let a = null
console.log(a ?? '空')        // 空

let a = undefined
console.log(a ?? '空')        // 空

let a = 0
console.log(a ?? '空')        // 0

let a = false
console.log(a ?? '空')        // false

The || operator is to take the data on the right as long as the data on the left is not true , so when the data on the left is 0 / false, it will also take the data on the right

Code example:

let a = 0
console.log(false || '空')        // 空

let a = false
console.log(false || '空')        // 空

let a = null
console.log(false || '空')        // 空

let a = undefined
console.log(false || '空')        // 空

 

Guess you like

Origin blog.csdn.net/qq_43551801/article/details/128228833