In Rails I can do this:
x = user.try(:name)
this method returns nil
if user
is nil
else user.name
You can use logical AND (&&
) operator. It works differently than in most of the languages because its result is not a boolean. For example:
const x = user && user.name;
The table below shows all possible outcomes of using this operator:
+--------------+-----------------------+
| user | x = user && user.name |
+--------------+-----------------------+
| undefined | undefined |
| null | null |
| {} | undefined |
| {name:''} | '' |
| {name:'Jon'} | 'Jon' |
+--------------+-----------------------+