Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript equivalent of Rails try method

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.

like image 974
tihom Avatar asked Oct 10 '13 01:10

tihom


People also ask

What is try method in Rails?

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.

How do you use try method?

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.


2 Answers

You can do this way, as there is no built in way of doing that:

var x = (user || {}).name; 
  • If user is not defined/null you will get undefined
  • If user is defined you will get the name property (which may be set or undefined).

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. 
like image 112
PSL Avatar answered Sep 27 '22 18:09

PSL


Optional Chaining Operator

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

like image 37
SiM Avatar answered Sep 27 '22 19:09

SiM