Cover
JavaScript

ES2020 fixes the Ampersand hell

Introduction
ES2020 fixes the Ampersand hell

If you are a Javascript developer I am pretty sure you have written things like this in the past:

object.prop.doSomething();

and JS comes along and slaps you in the face:

Uncaught TypeError: Cannot read property 'doSomething' of undefined

The reason for that is simple: prop does not exist on object for whatever reason.

Fixing it like 2019

In the past you had to enter something that I will describe as the Ampersand Hell, you had to go through each prop and make sure it exists, you end up with something like this to make sure your script won't crash:

if (object && object.prop && object.prop.doSomething) { ... }

ES2020 to the rescue!

With the upcoming Ecmascript Version for 2020 a new feature will be introduced, called optional chaining. This feature allows to add simple question marks ? behind the props to define them as optional. The fix to the code above would be as simple as:

object.prop?.doSomething?.();

Notice the .() notation to call optional methods. How great is that? Definitely a feature I have been waiting for a long long time.

I love that, I want it now

Babel has you covered! You can already use it via this plugin:

@babel/plugin-proposal-optional-chaining · Babel
## Example

Unfortunately you have to precompile your code with Babel, but let's be honest: who doesn't?

Read more

New JavaScript Features Coming in ES2020 That You Can Use Now
Since the release of ES6 in 2015, JavaScript has been evolving fast with tons of new features coming out in each iteration. The new versions of the JavaScript language specification have been updated…
What is Optional Chaining in JavaScript?
. Tagged with javascript, es2020, esnext.
Marc Mintel
Author

Marc Mintel

Marc Mintel is a self taught JavaScript and Frontend Developer with heavy focus on React and Vue.

View Comments
Previous Post

5 reasons you should abandon default exports

Success! Your membership now is active.