A friend of mine discovered some interesting behaviour in some Javascript code, which I decided to investigate further.
The comparison
(function (x) {return x*x;}) > [1,2,3]
returns true
in most major browsers (Firefox, Chrome, Opera and Safari) and false
in IE9. To me, there is no logical result of this comparison other than undefined
as there is no way to say that a function is greater than an array.
Reading up on this in the ECMA-script standard, it says that the actual arguments of >
when it is used on objects are the result of calling the ToNumber internal operation on the arguments. Some experiments and further reading tells me that this is not the same as applying a type conversion such as (Number) arg
. Reading the specification, I have a hard time figuring out what's going on here.
Can anyone fill me in on what's really happening here?
In IE<9, .toString
ing (function (x) {return x*x;})
gives
"(function (x) {return x*x;})"
While in chrome it gives:
"function (x) {return x*x;}"
If you compare:
"function (x) {return x*x;}" > "1,2,3" // true "(function (x) {return x*x;})" > "1,2,3" // false
Which is effectively the same as comparing:
"f" > "1" "(" > "1"
Which is the same as comparing:
102 > 49 40 > 49
So that's how we get from a function and array comparison to a simple number comparison :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With