0

When checking in chrome console running following statements return strange results.

0.5 < 0.6 < 0.7 => returns false

1.5 < 1.6 < 1.7 => return true

Can anyone explain this behaviour?

alert("0.5 < 0.6 < 0.7  = " + (0.5 < 0.6 < 0.7));
alert("1.5 < 1.6 < 1.7  = " + (1.5 < 1.6 < 1.7));
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
Sachin Joshi
  • 119
  • 5
  • I don't like these questions. There's already a million of them, someone meddling in a console and then being surprised. There's an infinity of possible combinations that you can run into console and ask SO question about it. – Tomáš Zato Jan 08 '16 at 10:47

3 Answers3

7

The expression

0.5 < 0.6 < 0.7

is evaluated, like this

(0.5 < 0.6) < 0.7

Since the first part is true, it will be effectively

true < 0.7

Both the sides will be tried to be converted to a number and since true is 1 when converted to a number, the expression becomes

1 < 0.7

which is not correct. That is why false is returned.


Same way, in the second case,

1.5 < 1.6

is true, so it becomes 1 and the expression becomes

1 < 1.7

which is true.


You can check the behaviour of booleans as numbers, like this

console.log(+true);
// 1
console.log(+false);
// 0
console.log(Number(true));
// 1
console.log(Number(false));
// 0
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1
0.5 < 0.6 // true

true became 1, because of the type changing to number

1 < 0.7 // false

the second one:

1.5 < 1.6 // true

true became 1, because of the type changing

1 < 1.7 // true
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

The associativity of < is from left to right. And a boolean true has a numerical value of 1, and false has a value of 0.

Putting this together:

  1. 0.5 < 0.6 < 0.7 is (0.5 < 0.6) < 0.7 is 1 < 0.7 is false.

  2. 1.5 < 1.6 < 1.7 is (1.5 < 1.6) < 1.7 is 0 < 1.7 is true.

where the parentheses make the associativity clear.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483