In Rails I can do this:
x = user.try(:name)
this method returns nil
if user
is nil
else user.name
Isn't that the same as what this gives you in Javascript:
user['name']
user.name
This returns undefined
instead of nil
but that's equivalent in most cases. I think the reason Rails needs the try
method is because you cannot access instance variables unless they are made accessible.
To add to @PSL's approach, I usually do something like:
var x = user || {},
y = x.name || {},
z = y.first_name;