zik
zik

Reputation: 3095

What is the correct syntax for this 'OR' and 'AND' in this 'IF' statement?

I've got an 'if' statement and just wanted to know if these are both valid (which I believe they are) and if so what is the difference?

var type;
var type2;

if ((type == 'BOS'|| type == 'BPS'|| type == 'BRS') && (type2 == 'BOS'|| type2 == 'BPS'|| type2 == 'BRS))

OR

if ((type == 'BOS') || (type == 'BPS') || (type == 'BRS') && (type2 == 'BOS') || (type2 == 'BPS') || (type2 == 'BRS'))

Which has the correct syntax and do they do anything differently? is there a way to shorten this statement?

Thanks

Upvotes: 0

Views: 342

Answers (3)

Kristiono Setyadi
Kristiono Setyadi

Reputation: 5643

Both conditional statement are valid but the result may be different.

The first statement will evaluate the OR value in the first bracket, and then evaluate the OR value in the second bracket, and finally evaluate the AND operator.

The second statement will evaluate the AND first and then evaluate from left to right without specific precedence (as in the first one).

You have to know which one do you actually use to determine the best refactoring code for it.

See this link: Operator Precedence.

Upvotes: 0

darnir
darnir

Reputation: 5190

The two statements are different. Yes, they are both valid statements, syntactically, but logically they differ. Since the && operator has a higher precedence than the || in javscript, the resulting logic will evaluate as follows in statement 2:

1) (type == 'BRS') && (type2 == 'BOS')
2) (type == 'BOS') || (type == 'BPS') || (result of 1) || (type2 == 'BPS') || (type2 == 'BRS')

While in statement 1:

1) (type == 'BOS'|| type == 'BPS'|| type == 'BRS')
2) (type2 == 'BOS'|| type2 == 'BPS'|| type2 == 'BRS')
3) (result of 1) && (result of 2)

Upvotes: 5

sergle.ua
sergle.ua

Reputation: 41

var type1;
var type2;

var correct_value = {
  BRS: 1,
  BOS: 1,
  BPS: 1
};

if( correct_value[type1] && correct_value[type2]) {
  alert('ok');
}
else {
  alert('not ok');
}

Upvotes: 3

Related Questions