1

I can't find an answer to this, after a little research.

Given this:

'Hello' || true ? true : false

The result is true, which to me, doesn't make sense. Because the first value was truthy, I would expect the result of this to be 'Hello', and skip the ternary. However, what it instead does is use the result of the ternary.

Why is that?

Joseph Shambrook
  • 320
  • 6
  • 14
  • Is the same as `if('Hello' || true) echo true;` the condition is `true`, so the output is "true" – toffler Dec 18 '18 at 15:34
  • `"I would expect the result of this to be 'Hello'"` Why? – j08691 Dec 18 '18 at 15:34
  • 5
    Operator precedence here... http://jsfiddle.net/briosheje/ys7zbn3x/ You probably are expecting the ternary operator to take precedence over the `||`, but it just doesn't. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence – briosheje Dec 18 '18 at 15:35
  • 1
    `'Hello' || (true ? true : false)` would satisfy your expectations. Or shorter: `'Hello' || true`. Or even shorter: `'Hello'`. – connexo Dec 18 '18 at 15:37

2 Answers2

6

it's because of the operators precedence in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

|| is interpretet before ?, hence it is an equivalent to:

('Hello' || true) ? true : false
andrusieczko
  • 2,824
  • 12
  • 23
2

It comes down to the priority of operations.

The || operator has a higher priority than ?:. This means that it's the same as this:

('Hello' || true) ? true : false

('Hello' || true) is truthy, so truthy ? true : false will return true

Errorname
  • 2,228
  • 13
  • 23