0

Why do i receive false if both variables have equal content?

function A() { return {k:'k'}; }
function B() { return {k:'k'}; }

var a = new A;
var b = new B;

 var s='';

for (prop in a) {
   if (typeof a[prop] != "function") {
       s += "a[" + prop + "] = " + a[prop] + "; ";
   }
}
alert(s);


for (prop in b) {
   if (typeof b[prop] != "function") {
       s += "b[" + prop + "] = " + b[prop] + "; ";
   }
}
alert(s);


alert( a == b ); // false?

http://jsfiddle.net/wZjPg/

same happens even if i assign both a and b same function

var obj = {};

function A() { return {k:'k'}; }

var a = new A;
var b = new A;

alert( a == b ); // false?

http://jsfiddle.net/3rzrR/

and same here

k={zor:1};
b={zor:1};

alert(k==b); //false

http://jsfiddle.net/5v8BJ/

Oriol
  • 274,082
  • 63
  • 437
  • 513
Sol
  • 337
  • 2
  • 8
  • 20

1 Answers1

7

That's because objects are compared by reference.

[] === []; // false

According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators,

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • so i must manually check all properties? – Sol Nov 02 '13 at 19:26
  • 2
    @Sol **You should define what you mean when you consider that two objects are the same, and test that**. For example, you could check if they have same properties (own / own+inherited), and if the properties are objects you must decide too if you will compare them using your own definition or by reference. – Oriol Nov 02 '13 at 19:27