-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 parentheses to get a boolean:

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

What is the explanation?

Note: This is not a duplicate of this question, which does not have anything about equality operators - JavaScript OR (||) variable assignment explanation

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user210757
  • 6,996
  • 17
  • 66
  • 115
  • 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
  • 1
    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
  • 1
    [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
  • 1
    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
  • 376,160
  • 25
  • 347
  • 392
4

|| is a short circuit operator and conditions are evaluated from left to right.

So in left || right, if the left condition is true, the whole condition is evaluated to true and the right one is never evaluated.

In

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 in

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
davidxxx
  • 125,838
  • 23
  • 214
  • 215