0

The priority of AND && is higher than OR ||. That's why it works before OR.

In the example below, 1 && 0 is calculated first.

alert( 5 || 1 && 0 ); // 5

I don't understand how this happens?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 6
    The `||` operator takes the left hand side as long as it is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). So `5 || /*anything*/` is 5. – Nicholas Tower Oct 07 '21 at 18:41
  • 1
    no it isn't. it's evaluating left to right like it's supposed to. `5` is a truthy value so it stops then and there since you're using the `||` operator – bryan60 Oct 07 '21 at 18:41
  • 1
    What do you not understand, exactly? Do you understand why 5 + 2 · 3 = 11 and not 21? – Sebastian Simon Oct 07 '21 at 18:41
  • 1
    This is just a convention and it is how the language is implemented. Here's the complete list of [operators precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) – user2314737 Oct 07 '21 at 18:41
  • 1
    See [Does JavaScript have "Short-circuit" evaluation?](/q/12554578/4642212). – Sebastian Simon Oct 07 '21 at 18:43
  • As you said, `&&` has an higher precedence over `||`, and then the condition can be rewritten `(5) || (1 && 0)`, the same way multiplication has an higher predecence over addition, `5 + 1 * 0` is equivalent to `(5) + (1 * 0)` – Cid Oct 07 '21 at 18:50
  • Are you trying to do bitwise operations like [`| OR`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR)? – Heretic Monkey Oct 07 '21 at 18:51
  • Your question would make more sense if it were `5 || foo() && bar()` and you wonder if foo and/or are bar are ever called. – Salman A Oct 07 '21 at 18:53

2 Answers2

0

The left-hand side will be evaluated first. Please see example

a || (b * c);  // evaluate `a` first, then produce `a` if `a` is "truthy"
a && (b < c);  // evaluate `a` first, then produce `a` if `a` is "falsy"
a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
a?.b.c;        // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined`

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

MartynFItz
  • 153
  • 1
  • 10
0

Please check Operator Precedence for more details.

Order is from left to right, when any of the early left part evaluates to be true, the rest of right side is not evaluated and is omitted.

console.log(5 || false); // 5
console.log(true || 5 || false); // true
console.log(false || 5 || 10); // 5
console.log(false || 10 || 5); // 10
Naveen Kumar V
  • 2,559
  • 2
  • 29
  • 43