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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s