Reputation: 103
I'm wondering how to combine and (&&) with or (||) in JavaScript.
I want to check if either both a and b equal 1 or if both c and d equal 1.
I've tried this:
if (a == 1 && b == 1 || c == 1 && d == 1)
{
//Do something
}
But it doesn't work.
How can I write this condition correctly?
Upvotes: 6
Views: 31608
Reputation: 1540
&&
precedes ||
. ==
precedes both of them.
From your minimal example I don't see, why it doesn't achieve your desired effect. What kind of value types do a–d have? JavaScript might have some non-obvious type coercion going on. Maybe try comparing with ===
or convert to numbers explicitly.
Side note: many lint tools for C-like languages recommend to throw in parentheses for readability when mixing logical operators.
Upvotes: 9
Reputation: 150010
Well now that I've finished telling everybody else (except David) why their answers are wrong, let me give them the same chance to hassle me.
Your existing code as shown should already do what you seem to be describing. But is it possible that when you say:
"I want to check if either both a and b equals 1 or if both c and d equals 1."
...your use of the word "either" mean that you want to check if one and only one of the following conditions is true:
That is, you want one pair of variables to be 1, but you don't want all four variables to be 1 at the same time?
If so, that is an exclusive OR operation, which in JS is the ^
operator:
if ((a == 1 && b == 1) ^ (c == 1 && d == 1)) {
Note that unlike with a logical OR ||
operator, you have to add parentheses around the AND &&
parts of the expression because ^
has higher precendence. (^
is actually a bitwise operator, but it will work for you here since the operands you'd be using with it are all booleans.)
Upvotes: 4
Reputation: 49362
Operator Precedence can be overridden by placing the expression between parenthesis.
if ((+a == 1 && +b == 1) || (+c == 1 && +d == 1)) // Use brackets to group them
{
// your code
}
This will prevent you from such cases like if(0&&0 || 1&&1)
.
Upvotes: 6
Reputation: 903
place some extra brackets to differentiate the and n or conditions
if ((a == 1 && b == 1) || (c == 1 && d == 1))
Upvotes: 1