0

In Ruby you can use the &. operator to return nil when chaining stuff on something that could or could not be nil. Like this:

Let's say we have the variable dog

dog might have an associated owner - if an owner exists, the owner do have a name. We would reach the owner name by doing this:

dog.owner.name

BUT, this might be a stray dog with no owner (yes, sad )

dog.owner == nil

when we then try to use name on nil we will get a NoMethodError: undefined method "name" for nil:NilClass

.. let's say that in this case the desired behavior would instead be to return nil.

That is easily done in ruby by using &. - like this:

dog.owner&.name - that will make a check "Is there a owner object here? No, ok, let's finish and return nil!"

This is VERY useful I would say. Maybe someone disagrees, that's fine but please refrain from starting that potential debate which would make this thread stray from my actuall question. Which is this:

Is there a equivalent operator like this for javascript?

Brainmaniac
  • 1,679
  • 2
  • 15
  • 39
  • var dog = {owner: {name: "owner name"}}; use dog.owner && dog.owner.name then var dog = {}; dog.owner && dog.owner.name; it will not throw any error – chans Apr 28 '20 at 05:48
  • Thank you but the linked question is has a better answer `dog.owner?.name` – Brainmaniac Apr 28 '20 at 05:50

0 Answers0