Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function is larger than an array?

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?

like image 594
evilcandybag Avatar asked Feb 21 '12 16:02

evilcandybag


1 Answers

In IE<9, .toStringing (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 :)

like image 159
Esailija Avatar answered Oct 04 '22 09:10

Esailija