Sachin Joshi
Sachin Joshi

Reputation: 119

Strange behaviour of javascript while chaining math comparison operators

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));

Upvotes: 0

Views: 75

Answers (3)

thefourtheye
thefourtheye

Reputation: 239453

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

Upvotes: 7

Bathsheba
Bathsheba

Reputation: 234665

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.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

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

Upvotes: 1

Related Questions