In Rails I can do this:
 x = user.try(:name)   this method returns nil if user is nil else user.name. Here name is a method defined on the user object.
I know it can be done using if..then..else in Javascript but is there an equivalent compact method to do the same in Javascript?
Googling points to Javascript's try command which is not what I am looking for.
In Rails, try() lets you call methods on an object without having to worry about the possibility of that object being nil and thus raising an exception. try.rb.
Try is a method that typically receives another method, which is denoted by a symbol. If the object is not nil, try will call the passed in method on the object. However, if it is nil, try will return nil.
You can do this way, as there is no built in way of doing that:
var x = (user || {}).name;   This won't break the script if user is not defined (null).
But user variable has to be declared some where in the scope, even though its value is not defined. Otherwise you will get the err saying user is not defined.
Similarly if is in global scope then you can explicitly check for this variable as a property of global scope, to avoid the error as mentioned above
ex:
 var x = (window.user || {}).name; // or var x = (global.user || {}).name;   For safe execution of functions,
 var noop = function(){}; //Just a no operation function   (windowOrSomeObj.exec || noop)(); //Even if there is no property with the name `exec` exists in the object, it will still not fail and you can avoid a check. However this is just a truthy check so you may want to use it only if you are sure the property if exists on the object will be a function. 
                        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 [email protected] 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With