4

How does the JS engine actually compare objects (like function declarations) for equality?

var f1 = function(){};
var f2 = function(){};

console.log(f1 === f2);  //false

what is actually happening behind the scenes to determine that the object references are different? Is it comparing memory locations?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 2
    If you wouldn't expect `new Object() === new Object()`, then why should you expect that `new Function() === new Function()`? – zzzzBov Aug 26 '16 at 04:59
  • Just saw your edit. In a nut shell, yes it's comparing memory locations. – Mike Aug 26 '16 at 05:14

3 Answers3

5

Functions are objects.
Different instances of objects are never srict(or non-strict) equal.

Strict equality applied by pointer:

var a = b = {}, c = {};
console.log(a === b, a === c); // true false
vp_arth
  • 14,461
  • 4
  • 37
  • 66
2
var foo = function() {
    a = 1;
 }; 

 var bar = function() {
    a = 1;
 }; 

alert(foo.toString() == bar.toString());​

this will return true.

pranav-dev
  • 68
  • 1
  • 2
    Yes but you're just comparing translated `string` values not the actual objects themselves. – Mike Aug 26 '16 at 05:17
  • @Mike is right. This has nothing to do with OP's question. – rgoliveira Aug 26 '16 at 05:36
  • 1
    Also, you can optimize your code by removing assignments to global `a` – vp_arth Aug 26 '16 at 05:36
  • Hm, for now I'm understand why this answer here. It just demonstrates a tricky(and not always correct) way to compare functions by their code. `foo.toString().replace(/\s+/g, ' ')` can be better some cases. – vp_arth Aug 26 '16 at 05:41
  • @Mike yes i have compared string values. Two objects arestored at two different locations. So when we try to compare we are actually trying to compare two different memory locations, those are always different. If they pointing to same location then only outcome will be true. ` var foo = function() { a = 1; }; var bar = foo; alert( foo == bar )` – pranav-dev Aug 26 '16 at 05:45
  • Sure but that isn't what OP was asking. – Mike Aug 26 '16 at 05:48
-4

== checks if the Values are equal

=== checks if the Values are equal along with the variable type or return type

teo van kot
  • 12,350
  • 10
  • 38
  • 70