-5

Why is the mid number result of this statement?

(0 || 0.571428571428571 || 1) == 0.571428571428571

How the comparsion works?


Well. Looks like stupid question. For those who works in php where this statement has a different result could be helpfull to know that JS will return number instead bool.

Jirka Kopřiva
  • 2,939
  • 25
  • 28
  • What did you expect the result to be, and why? – Pointy Jan 07 '16 at 21:31
  • Possible duplicate of [What does the construct \`x = x || y;\` mean?](http://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean) – Alex Jan 07 '16 at 21:40

3 Answers3

3

Your expression is interpreted as

((0 || 0.571428571428571) || 1)

The result of the first || is truthy, so that's the result of the overall expression. That's how || works: the result is the left-hand operand if it's truthy, or else the right-hand operand.

Pointy
  • 405,095
  • 59
  • 585
  • 614
3

|| is a short-circuiting operator. It evaluates its left-hand operand, and returns that if it's truthy, otherwise it evaluates and returns its right-hand operator. When you have a sequence of || operators, it performs this left-to-right, returning the first truthy value (or the last value if none are truthy).

In your example, 0 is falsey, so 0.571428571428571 is the first truthy value, and it's returned.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Barmar thnk you. The problem was i switched from PHP to JS. in PHP is result 1 or 0. I expected the same, not the number. – Jirka Kopřiva Jan 07 '16 at 21:52
  • In PHP, the logical operators always return a boolean result, rather than one of the arguments. – Barmar Jan 07 '16 at 21:53
1

The answer to this lies in the fact that 0 is considered a false value while non-zero numbers are considered true.

Since || and && will short circuit and return as soon as it knows the outcome. For OR expressions this means that the first truthy value will be returned. For AND expressions it means the first false value is returned:

(true && true && 0 && true) === 0
(false && false && 1) === 1

(false || false || 1 || false) === 1
(false || false || 0) === 0

Since the first value in your expression is a falsey value, it is not returned but the floating point is a truthy value, so it is returned.

Kevin Choubacha
  • 368
  • 3
  • 10