Using Safe Navigation while navigating chained objects
In object-oriented programming, the safe navigation operator (also known as optional chaining operator, safe call operator, null-conditional operator, null-propagation operator) is a binary operator that usually returns null if its first argument is null otherwise it performs a dereferencing operation as specified by the second argument instead of throwing an error.
Ruby
In Ruby
1
2
3
if event && event.details && account.details.venue
return account.details.venue
end
can be written as
1
return event&.details&.venue
using the safe navigation operator (&.
) which was a nice addition after Ruby 2.3.0.
Javascript
In JS, safe navigation is caled optional chaining. The optional chaining (?.
) operator accesses an object’s property or calls a function. If the object accessed or function called using this operator is undefined
or null
, the expression gets bypassed and evaluates to undefined
instead of throwing an error.
For example:
1
const place = event && event.details && event.details.venue;
can be written as
1
const place = event?.details?.venue