16 ноября 2012 г.

Strange Javascript comparison (WAT?!)

If you are familiar with Python comparison syntax like that:
a<b<c
Which means "b is greater than a and lesser than c", you will be surprized by Google Chrome JS engine behaviour. Look at this output:

0<1<2
true
0<1<2<3
true
0<1<2<3<4
true
0<1<2<3<4<3
true
0<1<2<3<4<3<2
true
0<1<2<3<4<3<2<1
false
0<1<2<3<4<3<2<1<0
false



WAT?! 0 < 1 < 2 < 3 < 4 < 3 is True?! 

To know why, read next.



And one more time:
6>5>3
false
6<5<3
true
Such discouraging behaviour can be explained: JS have NO ternary comparison like in Python. 
As I expect expressions will be evaluated as: 
  6 > 5 > 3  =>  6 > (True) => ?


6 > true
true

6>5>3
false

WAT?! 
In this expression true is evaluating to 1, so it will be evaluated this way:
6>5>3 => (6>5) > 3 => (true) >3 => 1 > 3 => false

So, never, NEVER try to do ternary comparisons in Javascript! 

Отправить комментарий