Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to combine optional chaining with arrays and map (in Javascript)?

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!

like image 590
Cerulean Avatar asked Feb 11 '20 08:02

Cerulean


People also ask

How do you use optional chaining in an array?

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 .

Does JavaScript support optional chaining?

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 .

What is the optional chaining?

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 .

When was optional chaining added to JavaScript?

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.


1 Answers

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

like image 110
Matthew Payne Avatar answered Sep 20 '22 08:09

Matthew Payne