Search code examples
javascriptecmascript-nextoptional-chaining

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?


Solution

  • 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 operator precedence. 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.