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 .
.