Categories
JavaScript Answers

How to use optional chaining with arrays and functions with JavaScript?

Spread the love

To use optional chaining with arrays and functions with JavaScript, we use the ?. operator.

For instance, we write

const item = myArray.filter((x) => x.testKey === myTestKey)?.[0];

to call filter to return an array with items in myArray where the testKey property equals myTestKey.

And we get the first item with the optional chaining operator with ?.[0].

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.