Optional Chaining Proposal
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:
- Hard to maintain and ugly code.
contactsobject does not exist,
userPhoneconstant will be
false. So imagine that we need to access a property
hasPaid. I think that it should be return
undefinedrather 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:
I also wrote a tiny ~300bytes library called MJN that can handle this problem!
Well, as you can see, we can handle that problem in few different ways… but not natively (yet!).
As you may guess, that particular problem exist in other languages… but they handle it! Let’s see some examples:
As you can see, Groovy and C# implements a similar control flow… and guess how does the EcmaScript Optional Chaining Proposal look?
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!
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?
Deleting properties is even easier!
Imagine doing this without the Optional Chaining Operator… how many
if statement would you write?