I am trying to reduce the function cognitive complexity required by SonarQube, I am wondering, are these two if statements equivalent?
The first statement:
if (
currentRef &&
currentRef.current &&
currentRef.current.value.length === 0
)
I want to replace it by :
if (
currentRef?.current?.value.length === 0
)
CodePudding user response:
Yes.
Optional chaining returns undefined
in case of an invalid reference. MDN docs state:
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
However, keep this in mind:
Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object.
Example
const dog = {'foo': 0};
console.log(dog?.foo === 0);
console.log(dog?.bar === 0);
CodePudding user response:
The two statements in your question are equivalent, which means that for a given value, they will both return either true
or false
.
It is important to mention that
if (currentRef?.current?.value.length === 0)
is the preferred syntax for these statements, since they also allow you to use a default value using nullish concealing.
No nullish concealing:
if (currentRef?.current?.value.length === 0)
// computes to false if 'currentRef or 'current' is undfined'
With nullish concealing:
if ((currentRef?.current?.value.length ?? 0) === 0)
// computes to true if 'currentRef or 'current' is undfined'