Asking for help, clarification, or responding to other answers.
The question mark after the variable is called Optional chaining (?.) in JavaScript. The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.
Yes, the "?:" operator will return the value to the left, if it is not null. Else, return the value to the right. "Yes, the "?:" operator will return the value to the left, if it is not null." - That is incorrect.
?.
is a null safe operator which is used to avoid unexpected NPE.
if ( a?.b ) { .. }
is same as
if ( a != null && a.b ) { .. }
But in this case is()
is already null safe, so you would not need it
other.is( this )
should be good.
There is a subtlety of ?.
, the Safe navigation operator, not mentioned in @dmahapatro's answer.
Let me give an example:
def T = [test: true]
def F = [test: false]
def N = null
assert T?.test == true
assert F?.test == false
assert N?.test == null // not false!
In other words, a?.b
is the same as a != null && a.b
only when testing for a boolean value. The difference is that the first one can either evaluate to a.b
or null
, while the second one can only be a.b
or false
. This matters if the value of the expression is passed on to another expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With