Today I found something in Javascript that just doesn’t make any sense. Ok, maybe some other things don’t make sense either, but I think this one just beats all of them.
Let’s say we have a string and a number:
a = "1";
b = 1;
Now we want to compare these:
alert((a>b) ' : ' (aa) ' : ' (b==a));
Both will give you ‘false : false : true’.
If we change a to “2”
a = "2";
b = 1;
we get a ‘true : false : false’. We’re still OK.
Now let’s change a to “a”
a = "a";
b = 1;
The weird thing is we get ‘false : false : false’ on both alerts.
In typestrict languages you’d get an error. Or at least you should. In php you get a ‘false : true : false’ and ‘true : false : false’ which would mean they decided that all strings are smaller than numbers. This is weird – if you make b a string “1” the return values change – but at least they made a choice.
For what I can comprehend Javascript casts both values to int and I can understand that. The core of the problem is obviously with the NaN value. What I can’t understand is how something’s not smaller, not bigger and not equal at the same time? I’m sure someone can explain this…
Is a dream bigger than an apple?
That’s how :)
I could accept that in typestrict languages. And I would even accept it here, but how come then
both return ‘1, a’. Doesn’t this mean that it decides that 1 is smaller than ‘a’ ?
I don’t know, it might. But my point is that if you go comparing uncomparable items, then you can reasonable expect undetermined result.