Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional chaining cause unexpected result when used in if statement

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?

like image 282
Nick Avatar asked Jun 26 '20 22:06

Nick


People also ask

How does optional chaining work in JavaScript?

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.

What is the purpose of optional chaining with function calls?

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?.

What is the purpose of the optional chaining error rule?

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)?.();

Can I use optional chaining with an undefined root object?

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 .


1 Answers

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.

like image 153
amrender singh Avatar answered Oct 11 '22 14:10

amrender singh