Which Logic Operator Takes Precedence

JTApps picture JTApps · Jun 22, 2012 · Viewed 21.8k times · Source

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!

Answer

Christoph picture Christoph · Jun 22, 2012

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 readabilities sake anyways!