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

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


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


It's not as nice as the ?. operator, but to achieve a similar result you could do:

user && user.address && user.address.postcode

Since null and undefined are both falsy values (see this reference), the property after the && operator is only accessed if the precedent it not null or undefined.

Alternatively, you could write a function like this:

function _try(func, fallbackValue) {    try {        var value = func();        return (value === null || value === undefined) ? fallbackValue : value;    } catch (e) {        return fallbackValue;    }}

Usage:

_try(() => user.address.postcode) // return postcode or undefined 

Or, with a fallback value:

_try(() => user.address.postcode, "none") // return postcode or a custom string


No. You may use lodash#get or something like that for this in JavaScript.