user2066808
user2066808

Reputation: 3

How to have multiple 'and' logical operators and an 'or' logical operator

It is slightly hard to explain but I want to do something that looks like this:

if(a === 4 && b === true && c === "words" || "numbersandwords")DoSomething();

but it ends running without it matching the first operators. I want to know how to have the last operator except 2 different inputs while still making sure the other criteria are met before running.

Upvotes: 0

Views: 4084

Answers (3)

jerry
jerry

Reputation: 2611

In JavaScript, like other languages, every operator (like && and ||) has a precendence that determines the order in which it's evaluated. && has higher precedence than ||, so it's evaluated first. Therefore, every term on the left is anded together. Even if they are all false, however, the overall result is true because it's ored with "numbersandwords", which evaluates to true (as does everything except 0, -0, null, false, NaN, undefined, or the empty string). The first thing you need to do is actually compare something (presumably c) to it. Then you can change the order of evaluation using parentheses, which has higher precedence than anything else:

if(a === 4 && b === true && (c === "words" || c === "numbersandwords")) DoSomething();

Alternatively, you can break the test up into several if statements if you may want to eventually do something slightly different based on the value of c (or it just better expresses your intent):

if(a === 4 && b === true)
{
    if(c === "words" || c === "numbersandwords")
    {
        DoSomething();
    }
}

Upvotes: 0

Sam
Sam

Reputation: 194

You just need to use parentheses, e.g.:

if(a == 4 && b == true && (c == "words" || c == "numbersandwords")) { DoSomething(); }

Upvotes: 2

Coin_op
Coin_op

Reputation: 10728

Just use a few brackets to separate your or parts and the and parts, and add the c === before the last string. Without that equality part at the end, the 'numbersandwords' string always equates to true.

if(a === 4 && b === true && (c === "words" || c === "numbersandwords")){
  DoSomething();
}

Upvotes: 1

Related Questions