I had an if statement in code which checks whether an object is defined and then check for equality for one of its properties. My if statement was like:
if(obj && obj.a !== x) { // do something }
But now I used optional chaining and changed my if statement to:
if(obj?.a !== x) { // do something }
But now my code is not working correctly in this case. The code enters if statement even when obj is undefined. Please could somebody explain why is this happening?
How does Optional Chaining work in Javascript? Optional chaining is a feature in Javascript which lets us access child properties of an object, even if the parent object doesn’t exist. It’s used when properties are optional on an object, so that instead of returning an error, we still get a result from Javascript.
Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found: let result = someInterface.customMethod?.
This rule aims to detect some cases where the use of optional chaining doesn’t prevent runtime errors. In particular, it flags optional chaining expressions in positions where short-circuiting to undefined causes throwing a TypeError afterward. (obj?.foo)?.(); (await obj?.foo)?.();
Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object. 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 .
But now my code is not working correctly in this case. The code enters if statement even when obj is undefined.
This is happening mainly because of precedence of operators. Optional channing (?.) has higher precedence than the And (&&) operator and strict inequality operator (!==).
Let me explain both the cases:
Case 1: if(obj && obj.a !== x) { // do something }
Here, && has lower precedence than !== . So this is comparison could be equivalent to or written as:
if(obj && (obj.a !== x)){// do something}
Here, the condition will never be executed if the obj is falsy or nullish.
Case 2: if(obj?.a !== x) { // do something }
Here, ?. has higher precedence than !== . So this is comparison could be equivalent to:
if((obj && obj.a) !== x) { // do something }
so in this case, if obj is nullish, we will always enter inside the if statement until x is not undefined.
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