Optional Chaining — A JavaScript journey #11

Yann

Yann


Jul 9th 2019 in Développement web

It's the future feature of JavaScript that I'm the most excited about: optional chaining. And I'm sure you too without even knowing it. So, what is exactly optional chaining and how it can really help to produce a cleaner code.


The proposal

Two years ago, Claude Pache, Gabriel Isenberg and Dustin Savery proposed optional chaining to TC39. Their goal is to reduce repetition and/or intermediate assignment in deep property access.

Take this (too) common examples:

Not very slight, right? Sure, there are other strategies, but with optional chaining, you'll be able to achieve the same behaviour doing something like:

Is it not sooo much better? With just a simple ?., you can test every level of your property access chain. This is the official proposal syntax :

Finally, it's not something completely new in programming language; C#, Swift, CoffeeScript and others have similar features. We just have to wait a little bit more to see it in our plain JavaScript!


Status

Actually, the proposal is in stage 2. It means it already pass the proposal phase and it's now in draft. During this phase, the authors have to “precisely describe the syntax and semantics using formal spec language”. They already written the initial spec text and there is a fully working Babel plugin. So we can be optimistic about an upcoming stage 3.


Using it now

Babel plugin means that you can use this feature right now! Keep in mind that this is still not a final JavaScript feature, but this way you can test the concept and send feedback to the authors.

So, first install the dependencies :

Then, in your .babelrc:

And finally, just use your Babel to compile your *code:

*Take a look at the compiled code, it's fun to see how it's translated into old ES5


Conclusion

It's coming soon and it's going to be great! We can't say when it will be released, those things take time, but hopefully in 2020 if it's not in 2019. Keep in touch and try the Babel plugin in the meantime.