-1

According to Mozilla, the === operator has higher precedence than the || operator, which is what I would expect.

However this statement evaluates to the number 1, rather than false.

let x = 1 || 0 === 0; // x === 1;

You have to wrap in parens to get a boolean:

let x = (1 || 0) === 0; // x === false;

What gives?

NOTE this is not a dup of this question, which does not have anything about equality operators - JavaScript OR (||) variable assignment explanation

user210757
  • 6,196
  • 16
  • 59
  • 105
  • 3
    It evaluates left to right. The left side of the `||` evaluates to a truthy value so the right side of the `||` never gets evaluated. – Will Aug 30 '17 at 20:31
  • Possible duplicate of [JavaScript OR (||) variable assignment explanation](https://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation) – Steven Goodman Aug 30 '17 at 20:33
  • [Short-circuit evaluation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-circuit_evaluation) – j08691 Aug 30 '17 at 20:33
  • As Will said, this is a characteristic of how boolean OR (`||`) works and not an issue of operator precedence. – Steven Goodman Aug 30 '17 at 20:33
  • Along with generators, `||` and `&&` are seldom examples of lazy evaluation in JS. – Redu Aug 30 '17 at 20:38

2 Answers2

4

Higher operator precedence is like a parenthesis around the operands.

let x = 1 || (0 === 0);

The second part gets never evaluated, because of the truthy value of 1 .

Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
4

|| is a short circuit operator and conditions are evaluated from left to right.
So here : left || right, if the left condition is true, the whole condition is evaluated to true and the right one is never evaluated.

Here :

let x = 1 || 0 === 0; // x === 1;

x = 1 assigns 1 to x and the second condition after || is never evaluated as if (1) is evaluated to true.

And here :

let x = (1 || 0) === 0; // x === false;

(1 || 0) is evaluated to true as if (1) is still evaluated to true.
And then true === 0 is evaluated to false.
So x is valued to false.

davidxxx
  • 115,998
  • 20
  • 192
  • 199