Search code examples
javascriptoperatorslogical-operatorsoperator-precedence

Combining && with || in an if statement


I want to have a short if statement on one line that checks if condition A is met and then check if condition B is met, where both conditions are specific strings, but condition B has more than one valid option.

if (cond_A === 'Bradley' && cond_B === 'April' || cond_B === 'May') { ... }

This seems to work, but is it safe from giving unexpected/undesired results? Undesirable in this case would be interpreting just cond_B === 'May' as meeting the conditions. I guess I'm asking about order of operations: does && have precedence over || ? I want the results to be the same as

if (cond_A === 'Bradley') { 
    if (cond_B === 'April' || cond_B === 'May') {
        ... 
    } 
}

Thank you.


Solution

  • You can express conditions like this with brackets to force a particular order of evaluation:

    A && B || C
    (A && B) || C // How it is evaluated
    A && (B || C) // Likely how you want it evaluated
    

    The last form there is logically equivalent to your nested if approach. The need for the explicit ordering is because && has a slightly higher precedence than || in JavaScript.

    You can also use a different tool:

    A && ["1", "2", ...].includes(B)
    

    Where you can check for things in a list via includes(). This can express your intent more clearly, and scales better to larger lists of possible matches. For really large lists called really often you may even want to use a Set.