Optional Chaining in JavaScript

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

code1

What could be coming?

Rather than all that checking we can chain optional checks like this:

code2

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:

code3

At the same time, we can check for a function too:

code4

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