Optional chaining is in stage 1 and can be found in this repo. Optional Chaining provides a succinct way to check for the existence of an object before accessing its properties. Very similar to the C# null conditional operator. And it is already available in the React ecosystem.
Why do we need this?
What could be coming?
Rather than all that checking we can chain optional checks like this:
The main concern here is to make suremis the syntax is is question followed by a period: “ ?.”. Never just “?” without a “.” period.
We can use the optional chaining operator to access an item in an array like this:
At the same time, we can check for a function too:
How does it work?
The operator checks if whatever is on the left-hand side of the “?.” Is null or undefined. If it is, it causes a short-circuit then returns undefined otherwise it continues.
When can we use it?