Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of expression where the precedence of AND (&&) over OR (||) matters?

In all of the JavaScript operator precedence charts I can find (like this one and this one), the logical AND (&&) has slightly higher precedence to the logical OR (||).

I can't seem to figure out an expression where the result is different than it would be if they had the same precedence. I figure there must be some way for it to matter or they'd be listed as having the same precedence if it didn't.

For example:

0 || 2 && 0 || 3

is 3, but it doesn't matter how I slice that up, it's always going to 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 that first 0 something else (like 4), the result is always 4 because the first || doesn't even look at the right-hand side. If I swap the 0 and 3 in the last || around, the result remains 3.

The closest I've come is

0 || false && "" || NaN

...which is NaN, whereas

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

...is false, but I think that's explained purely by the left-to-right semantics, not by && being higher precedence.

I must just be missing it, for what expression does it matter that && has a higher precedence than ||?

like image 861
T.J. Crowder Avatar asked May 01 '15 10:05

T.J. Crowder


1 Answers

true || false && false

is true

(true || false) && false

is false

true || (false && false)

is true

like image 149
Ôrel Avatar answered Sep 20 '22 02:09

Ôrel