Reputation: 409
function foo(){
console.log( function(){return 1} <= function(){return 1} );
}
foo();
The above code prints "true". It prints true for both <= and >= , For all other operators it is "false".
What trick going on here?
Upvotes: 2
Views: 76
Reputation: 19080
function(){return 1} <= function(){return 1}
transforms the functions to a primitive. A function transformed to a primitive evaluates to it's code in a string (calling toString()
).
Then "function (){return 1}" <= "function (){return 1}"
performs an less or equal comparison on strings, which is true
.
In function(){return 1} == function(){return 1}
JavaScript compares the function objects. But because these are different instances, you'll have false
.
You can check more about equality operator in this article.
Upvotes: 2
Reputation: 22395
Because it's not comparing the returned 1
, it's comparing the functions
. When you run an operator on a function, it implicitly calls toString
.
As for ==
, Dmitri explained it well enough that toString
is not being called, but it runs an object comparison, which will be false because 2 different objects are never the same.
Here is the ECMA spec On relational operators, which explains how it operates with comparison operations. With objects, instanceOf
is used.
Upvotes: 3
Reputation: 11
Because it´s always is comparing 1 <= 1, and it´s true. If you compare 1 >= 1 is the same always it´s true. But if you compare 1 > 1 it´s false.
Upvotes: -1