Optional Chaining Proposal

Let’s face it: JavaScript objects sometimes can be both awesome and scary. They are super flexible, but they often lead to a big problem.
Let’s take the following example and pretend that this data comes from a database:

We may want to access the user phone number… but what if he hasn’t compiled it yet? What if the object above has changed for some reason, and we don’t have the contatcs object anymore?

Holy guacamole! That is such a frequent error! And how many times did you come up with the following solution?

Of course it works… but there are two problems with this code:

  1. Hard to maintain and ugly code.
  2. If contacts object does not exist, userPhone constant will be false. So imagine that we need to access a property hasPaid. I think that it should be return undefined rather than false if the property does not exist, doesn’t it?

Quick and dirty solutions

Great libraries like Ramda and Lodash provides their own way to handle this problem:

Lodash
Ramda

I also wrote a tiny ~300bytes library called MJN that can handle this problem!

If the desired key does not exist, MJN synchronously returns a callback value.

Well, as you can see, we can handle that problem in few different ways… but not natively (yet!).

Other Languages

As you may guess, that particular problem exist in other languages… but they handle it! Let’s see some examples:

Groovy
Ruby
C#

As you can see, Groovy and C# implements a similar control flow… and guess how does the EcmaScript Optional Chaining Proposal look?

EcmaScript Proposal

Ta-da! EcmaScript proposal looks very similar to the C# and Groovy implementation! I love it!
Let’s see how to use it today:

First of all, install Babel in your project:

Then make sure that your package.json file looks like this:

Last but not least, create a .babelrc file and fill it with the following JSON:

Ok great! Now we’re ready to go!

Getting Data

We’re gonna start with the example above: how do we get nested data?

So easy! And what if we try to access a property that does not exist?

We got undefined! Great!

Deleting Properties

Deleting properties is even easier!

Imagine doing this without the Optional Chaining Operator… how many if statement would you write?