Null-safe property access (and conditional assignment) in ES6/2015

ᆼᆺᆼ picture ᆼᆺᆼ · Aug 21, 2015 · Viewed 93.4k times · Source

Is there a null-safe property access (null propagation / existence) operator in ES6 (ES2015/JavaScript.next/Harmony) like ?. in CoffeeScript for example? Or is it planned for ES7?

var aThing = getSomething()
...
aThing = possiblyNull?.thing

This will be roughly like:

if (possiblyNull != null) aThing = possiblyNull.thing

Ideally the solution should not assign (even undefined) to aThing if possiblyNull is null

Answer

basicdays picture basicdays · Jan 27, 2017

Update (2020-01-31): Seems people are still finding this, here's the current story:

Update (2017-08-01): If you want to use an official plugin, you can try the alpha build of Babel 7 with the new transform. Your mileage may vary

https://www.npmjs.com/package/babel-plugin-transform-optional-chaining

Original:

A feature that accomplishes that is currently in stage 1: Optional Chaining.

https://github.com/tc39/proposal-optional-chaining

If you want to use it today, there is a Babel plugin that accomplishes that.

https://github.com/davidyaha/ecmascript-optionals-proposal