3-Dec

JavaScript

Elvis Operator

How to rock and roll with Optional Chaining

2 min read

·

By Henrik Hermansen

·

December 3, 2018

Elvis Presley Operator

Are you being a responsible developer and rocking your undefined-checks to prevent TypeError like this?

const street = customer && customer.address && customer.address.street;

That's nice, but you may have noticed it doesn't roll very well. While it's great to protect yourself from type errors, it can get tedious and cumbersome, and it doesn't feel very DRY.

I hope this won't leave you all shook up. Instead, you should read on - it's now or never!

Rock and roll 🕺

As you learned on Day 1 JavaScript is always open for suggested features and additions. One of these suggestions is called "Optional Chaining", and is about the operator best known as the Elvis operator.

The suggested operator looks like this ?., and you can use it to chain undefined-checks:

const street = customer?.address?.street;

This will check if both customer and address is present, and give you the value of street. However, if customer does not have the property address, or if customer.address does not have the property street, your variable will receive the value undefined, and no type errors are thrown.

You can even use this to safely (kinda) run functions or access items in an array:

customers?.[2];
api?.getCustomer?.();

This will make sure both api and api.getCustomer is present, before trying to run getCustomer. Beware though, that this will still throw a type error if getCustomer is not a function.

Could I go wrong with this?

Yes, there are some limitations and gotchas to this feature.

The biggest pitfall might be that each operator will only check the current link in the chain:

customer?.address.street; // will throw an error if address is undefined
customer.address?.street; // will throw an error if customer is undefined

For more details I suggest you have a closer look at The Proposalthe proposal.

Awesome! When can I use it?

Now! While the feature is currently in stage 1, it is of course available as a babel plugin.

I don't know about you, but I just can't help falling in love.

Up next...

Loading…

Loading…