current position:Home>JavaScript optional chain

JavaScript optional chain

2022-04-29 04:28:02@huihui_ new

Optional chain ?.

Optional chain ?. Is a secure way to access the properties of nested objects . Even if the intermediate attribute doesn't exist , There will be no mistakes .

For example, access the following objects :
const user = {}
If you pass user.address.id This way to access non-existent properties id, You're going to report a mistake ,
Can pass
(1).user && user.address && user.address.id
perhaps
(2).user ? (user.address ? user.address.id : ‘’ ): ''
These two ways to visit

But it will feel uncomfortable , First, the deeper the nesting, the more repetitive the code will be written , The deeper the second nesting, the more difficult it will be to understand ,

In this case, you can pass
user?.address?.id
Way to visit , If there is no attribute in the optional chain , Returns the undefined

Be careful
(1) Don't overuse optional chains
We should just ?. Use it in places where things don't exist .

for example , If according to our code logic ,user The object must exist , but address It's optional , So we should write like this user.address?.street, Not like this user?.address?.street.

therefore , If user It happened that the mistake turned into undefined, We'll see a programming error and fix it . otherwise , Errors in the code are eliminated in inappropriate places , This makes debugging more difficult .

(2) ?. The variable before must have been declared
If the variable is not declared user, that user?.anything Will trigger an error :

// ReferenceError: user is not defined
user?.address;
?. The variable before must have been declared ( for example let/const/var user Or as a function parameter ). Optional chains only apply to declared variables .

Other variants :?.(),?.[]
obj?.prop —— If obj To be is to return obj.prop, Otherwise return to undefined.
obj?.[prop] —— If obj To be is to return obj[prop], Otherwise return to undefined.
obj.method?.() —— If obj.method If it exists, call obj.method(), Otherwise return to undefined.

copyright notice
author[@huihui_ new],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/117/202204270551339365.html

Random recommended