-1

The below javascript function outputs as false, why is it resulted in false ?

console.log(15 > 10 > 5);
melpomene
  • 84,125
  • 8
  • 85
  • 148
soccerway
  • 10,371
  • 19
  • 67
  • 132
  • 1
    Because `1 > 5 === false`. – Teemu Dec 09 '18 at 19:10
  • 1
    by that statement you probably mean (15 < 10) && (10 > 5), and I believe by saying 15 > 10 > 5 what you actually do is (15 > 10) > 5, which gives you true > 5 – Tomasz Rup Dec 09 '18 at 19:10
  • 3
    Possible duplicate of [Strange behaviour of javascript while chaining math comparison operators](https://stackoverflow.com/questions/34674836/strange-behaviour-of-javascript-while-chaining-math-comparison-operators) – melpomene Dec 09 '18 at 19:11
  • 2
    Better duplicate: https://stackoverflow.com/questions/4089284/why-does-0-5-3-return-true – melpomene Dec 09 '18 at 19:12
  • Possible duplicate of [Why does (0 < 5 < 3) return true?](https://stackoverflow.com/questions/4089284/why-does-0-5-3-return-true) – shkaper Dec 16 '18 at 17:29

2 Answers2

3

Because comparison operators takes two operands. So first, your code evaluates 15 > 10 which returns true and so then it does true > 5 which obviously returns false

Pierre Capo
  • 1,033
  • 9
  • 23
  • 5
    It's not that obvious at all why `true > 5` is false. – axiac Dec 09 '18 at 19:11
  • 2
    true is equal to 1, here you go – Tomasz Rup Dec 09 '18 at 19:11
  • more exactly, `true > 5` makes no sense. However, `true` can be cast into a number, resulting in `1`. So `true > 5` will get cast into `1 > 5` which is `false`. Because of the above, `15 > 10 > -5` will return `true`. – Badashi Dec 09 '18 at 19:12
2

The comparison operators take two operands and associates from left to right. This means the expression 15 > 10 > 5 is evaluated as (15 > 10) > 5.

15 > 10 obviously evaluates to true.

true > 5 is not that obvious how it is evaluated.

Fortunately, the JavaScript documentation explains how the values are converted when they have different types:

If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.

This means true > 5 is evaluated the same way as 1 > 5 and only now the result is clear: it is false.

axiac
  • 68,258
  • 9
  • 99
  • 134