Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Logic Operator Takes Precedence

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!

like image 682
JTApps Avatar asked Jun 22 '12 14:06

JTApps


People also ask

Which operator is the highest precedence?

When two operators share a single operand, the operator having the highest precedence goes first. For example, x + y * z is treated as x + (y * z), whereas x * y + z is treated as (x * y) + z because * operator has highest precedence in comparison of + operator.

Which operator has the same precedence?

The precedence of Division and Multiplication arithmetic operators is the same.


2 Answers

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!

like image 105
Christoph Avatar answered Oct 17 '22 13:10

Christoph


There is a pretty good rule of thumb to this. Think of these operators as of mathematical ones:

  • AND is multiplication (eg. 0 * 1 = 0 => FALSE)
  • OR is adding (eg. 0 + 1 = 1 => TRUE)

When you remember this, all you have to know is that multiplication always comes before addition.

like image 33
Michal Leszczyk Avatar answered Oct 17 '22 11:10

Michal Leszczyk