1

just have 2 question regarding JS conditional operator, is the below 2 expression valid?

1.

if(isUser && isUser === true || isGuest && isGuest === true){
     //...
   }

I am wondering do I have to add () to make it like and still have the same functioning:

if((isUser && isUser === true) || (isGuest && isGuest === true)){
     //...
   }
const items = list.orderList && list.orderList.isUser === true || list.orderList.isGuest ? list.items : [];

I am wondering do I have to add () to make it like and functioning the same as above conditional operator:

const items = list.orderList && (list.orderList.isUser === true || list.orderList.isGuest === true) ? list.items : [];
3
  • 3
    Think of && and || as * and +. The && operator binds more tightly than ||. Commented Jun 18, 2021 at 17:44
  • 1
    Yes, the expressions in #1 are equivalent, but really you should write just if (isUser || isGuest) (or if (isUser === true || isGuest === true) if the variables can hold non-boolean values, but you should avoid that). The expressions in #2 are not equivalent. Commented Jun 18, 2021 at 17:46
  • Compare false && false || true vs false && (false || true) in the console. Commented Jun 18, 2021 at 17:51

1 Answer 1

3

As per Operator Precedence in the MDN docs, logical AND takes precedence over logical OR. Therefore,

expression1 || expression2 && expression3

will evaluate to

expression1 || (expression2 && expression3)

Therefore,

isUser && isUser === true || isGuest && isGuest === true

naturally evaluates to

(isUser && isUser === true) || (isGuest && isGuest === true)

anyway, so you do not need parentheses..

But since, in your second example, you want to evaluate OR then AND, you do need parentheses for it to evaluate the way you require, as

list.orderList && list.orderList.isUser === true || list.orderList.isGuest

will evaluate to

(list.orderList && list.orderList.isUser === true) || list.orderList.isGuest
Sign up to request clarification or add additional context in comments.

2 Comments

statement1 && statement2 || statement3 is pretty unambiguous since it would be evaluated the same if operator precedence would be the same and evaluation just left-to-right. statement1 || statement2 && statement3 = statement1 || (statement2 && statement3) might be a better example.
(Also, it should be expressionX not statementX)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.