I recently learned about optional chaining in Javascript and have been making use of it in a React/NodeJS project. Works great.
I noticed I have been using it with arrays map
, even without thinking about it much -- it seemed a natural use (here items
is an array, or possibly undefined
)
{items?.map(postListItem => ....
That is, it will map if items
exists, but not if items
is undefined
, but would avoid any run-time errors if I were to call map
on undefined
Nonetheless I don't know if this is an acceptable use or whether I'm mis-using optional chaining. I searched for an answer but as of yet haven't been able to find one, which makes me suspect I'm mis-using it. Any info much appreciated!
The optional chaining operator ( ?. ) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid. The ?. operator is like the .
Introduction to the JavaScript optional chaining operator allows you to access the value of a property located deep within a chain of objects without explicitly checking if each reference in the chain is null or undefined .
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil . If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil , the property, method, or subscript call returns nil .
Optional chaining was introduced in ES2020. According to TC39 it is currently at stage 4 of the proposal process and is prepared for inclusion in the final ECMAScript standard.
See answer here regarding the typescript usage. You need a period for array null safe Optional Chaining.
this.mostRecentMfaAttempt = this.verificationsAttempts?.content?.[0]
How to use optional chaining with array in Typescript?
Using optional chaining operator for object property access
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With