Is there a null
-safe property access (null propagation / existence) operator in ES6 (ES2015/JavaScript.next/Harmony) like ?.
in
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