In Rails I can do this:
x = user.try(:name)
this method returns nil
if user
is nil
else user.name
Is a new proposal for ECMAScript.
It is in an early stage but we can start using it with babel.
This is the problem:
const person = {name: 'santiago'}
let zip = person.address.zip // Cannot read property 'zip' of undefined
This is how it works:
const person = {name: 'santiago'}
let zip = person?.address?.zip // undefined
To start using it we need babel alpha 7:
npm install --save-dev babel-cli@7.0.0-alpha.19
npm install --save-dev babel-plugin-transform-optional-chaining@^7.0.0-alpha.13.1
And we need to add the plugin to our .babelrc
{
"plugins": ["transform-optional-chaining"]
}
Adam Bene Medium Post which explains how to use it and another use cases