PeteyRedbeard
PeteyRedbeard

Reputation: 48

Complex IF statement issue

There is a complex condition in an if statement and somehow it doesn't work out how I want.

if (
    (statementA1) ||
    (statementA2) &&
    (statementB) &&
    (statementC)
) {
    doSomething
}

Both A1 and A2 can't be true at the same time (because of the nature of the actual statement). Also, both B and C has to evaluate true in order to result in an overall true. So only for true false true true and false true true true should return true; any other permutation should return false.

The statements are in braces because of their inner complexity (including Math.abs(), A1 and B have inner, combined substatements).

Upvotes: 1

Views: 128

Answers (2)

user663031
user663031

Reputation:

Remember the acronym "Please Excuse My Dear Aunt Sally", or PEMDAS, which refers to Parenthesis, Exponentiation, Multiplication/Division, and Addition/Subtraction. That is the order of precedence, from higher (tighter) to lower (looser), in many languages, including JavaScript.

A variant is "Please Excuse My Aunt" (PEMA).

Then remember that in the logical world and is sort of like multiplication, and or is sort of like addition. That way you can remember that and (&&) binds tighter than or (||).

Therefore, if you want to and together two conditions, one of which is itself or'ing two conditions, you must parenthesize the latter:

a && (b || c)

Without the parens, it would be interpreted as

(a && b) || c

Of course, in your particular case you can avoid worrying about precedence and parentheses by simply writing

a1 != a2 && b && c

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386600

For

  a1    a2    b     c   result
----- ----- ----- ----- ------
true  false true  true  true
false true  true  true  true
true  true  true  true  true  <- different from blow

you can use this expression

(a1 || a2) && b && c

Either a1 or a2 and b and c.

if ((statementA1 || statementA2) && statementB && statementC) {
    // doSomething
}

You need the parenthesis because of the operator precedence of logical AND && (6) over logical OR || (5)

If you have the case

  a1    a2    b     c   result
----- ----- ----- ----- ------
true  false true  true  true
false true  true  true  true
true  true  true  true  false <- different from above

then you could use this expression

(!a1 && a2 || a1 && !a2) && b && c

which check a1 and a2 separately.

if ((!statementA1 && statementA2 || statementA1 && !statementA2) && statementB && statementC) {
    // doSomething
}

Upvotes: 4

Related Questions