Reputation: 1244
I have been trying to understand Javascript equality. Can you please tell me why the following line returns false
?
alert((function a(){}) == (function a(){})) // false
But as you can see from the following cases <
returns false
but <=
returns true
, which means ==
should return true
but it is false
. Do you have any idea, WHY?
alert((function a(){}) < (function a(){})) // false
alert((function a(){}) > (function a(){})) // false
alert((function a(){}) <= (function a(){})) // true
alert((function a(){}) >= (function a(){})) // true
Upvotes: 3
Views: 605
Reputation: 3382
A little known fact is that Javascript equality operator is actually === not ==. When you run a comparison operator on a function, you are comparing the value of the reference (the location in memory) not the function itself. Since the functions are all separate objects, == will not return true.
From "Javascript - The Definitive Guide" http://docstore.mik.ua/orelly/webprog/jscript/ch05_04.htm
On the other hand, objects, arrays, and functions are compared by reference. This means that two variables are equal only if they refer to the same object.
Upvotes: 1
Reputation: 140
If we test that the functions are not equal, we get true.
alert((function a(){}) != (function a(){})) //true
This is because each of the functions are a different object and why the equality check returns false.
Upvotes: 0
Reputation: 160833
You are comparing two object using <
, <=
, and they are actually compared with string they could covert to.
"function a(){}" < "function a(){}"
is false.
"function a(){}" <= "function a(){}"
is true.
EDIT:
Why (function a(){}) == (function a(){})
returns false is because you are compare same type with ==
, so they don't need to covert to string or number to compare, they are two different objects.
Upvotes: 5