Categories
JavaScript Answers

How to use optional chaining with array or functions with JavaScript?

Spread the love

Sometimes, we want to use optional chaining with array or functions with JavaScript.

In this article, we’ll look at how to use optional chaining with array or functions with JavaScript.

How to use optional chaining with array or functions with JavaScript?

To use optional chaining with array or functions with JavaScript, we use ?. in place of ..

For instance, we write

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

to call myArray.filter with a callback to find the entry with the testKey property equal to myTestKey.

Then we use ?. before [0] to return undefined if there’re no entries returned by filter instead of throwing an error.

?. is the optional chaining operator.

Conclusion

To use optional chaining with array or functions with JavaScript, we use ?. in place of ..

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *