Optional Chaining in JavaScript
Interactive Business Systems is now Planet Technology. Looking for a new job? We work with some of the biggest names in tech, and we’re hiring! Check out our open jobs and make your next career move with Planet.
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?
How often are we checking for existence of an object after an API call? Yes, almost always requiring us to write code like this to prevent errors due to JavaScript’s nature of allowing unstructured anonymous objects.
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?
It’s still a proposal so it’s not in Vanilla JavaScript just yet. However, it is usable with Babel!