javascriptif-statementlogicoperator-precedence

Which one of the logical AND (`&&`) and logical OR (`||`) operators take precedence over the other?


So, I'm looking into writing a slightly more complex operation with logic operators in an if-else statement. I know I can do parentheses, and I know it's the better way of doing this, but I've gotten curious and so I'm going to ask. If I were to do something like this:

if (firstRun == true || selectedCategory != undefined && selectedState != undefined) {
//Do something
} else {
//Do something else
}

How will that be operated without the use of parentheses? I know there is an order of operations for logic operators, similar to PEMDAS, right? I'm curious if it'll be ran something like this:

firstRun == true || (selectedCategory != undefined && selectedState != undefined)

or maybe if the 'OR' operator takes precedence instead and it ends up going like:

(firstRun == true || selectedCategory != undefined) && selectedState != undefined

The full list would be nice, if you can find it somewhere, of the order of operations for this. Thanks!


Solution

  • My rule of thumb, which covers basically 99% of all use cases for conditional statements, is:

    1. Grouping: ()
    2. Member access . or [...]
    3. Not: !
    4. Comparison, e.g. < , >= , === , !=, ...
    5. Logical AND &&
    6. Logical OR ||

    MDN gives you the exhaustive breakdown: JavaScript Operator Precedence

    So for your example:

    (firstRun == true || selectedCategory != undefined && selectedState != undefined)
    

    equals

    (firstRun == true) || ((selectedCategory != undefined) && (selectedState != undefined))
    

    For anything more complex than the above mentioned cases, I would look into refactoring the code for readability's sake anyway!