An example of an expression in which AND (&&) takes precedence over OR (||)?

In all JavaScript JavaScript priority diagrams, I can find (for example this and this ), logical AND ( && ) has a slightly higher priority for logical OR ( || ).

It seems I can not understand the expression in which the result is different from the result if they had the same priority. I believe that for this it must be somehow, or they will be indicated as having the same priority if it is not.

For instance:

 0 || 2 && 0 || 3 

there are 3 , but no matter how I cut it, it will always be 3 :

 (0 || 2) && 0 || 3 0 || (2 && 0) || 3 (0 || 2 && 0) || 3 0 || 2 && (0 || 3) 0 || (2 && 0 || 3) 

If I make this first 0 something else (like 4 ), the result will always be 4 , because the first || doesn't even look to the right. If I exchange 0 and 3 in the last || around, the result remains 3 .

Closest i came

 0 || false && "" || NaN 

... which is NaN , whereas

 0 || false && ("" || NaN) 

... there is false , but I think this is due to pure semantics from left to right, and not to && a higher priority.

I just need to skip it, for what expression does it mean that && has a higher priority than || ?

+5
source share
3 answers

If they had the same priority and were left-associative, then, for example, the expression

 1 || 0 && 2 

will be

 ((1 || 0) && 2) // evaluates to 2 

instead

 (1 || (0 && 2)) // evaluates to 1 

which we get from the "ordinary" priority rules.


For your structure … || … && … || … … || … && … || … … || … && … || … (which will be (((… || …) && …) || …) instead of the usual ((… || (… && …)) || …) ), you will get different results for values ​​such as 0 0 1 0 .


Why does logical AND have a slightly higher priority for logical OR?

So, the canonical form of Boolean expressions, the disjunctive normal form , does not need parentheses.

+3
source
 true || false && false 

is true

 (true || false) && false 

there is false

 true || (false && false) 

is true

+3
source

Example:

1 || 0 && 0 1 || 0 && 0 β†’ (1 || 0) && 0 β†’ (1) && 0 β†’ 0
1 || 0 && 0 1 || 0 && 0 β†’ 1 || (0 && 0) 1 || (0 && 0) β†’ 1 || (0) 1 || (0) β†’ 1

+1
source

All Articles