Javascript object comparison
-
$(document).ready(function(){
var obj1 = { }
var obj2 = { }
if(obj1 === obj2)
{
alert('true');
}
else
{
alert('False');
}
});Why if(obj1 == obj2) returns false eventhough obj1 and obj2 are objects of same type?
-
$(document).ready(function(){
var obj1 = { }
var obj2 = { }
if(obj1 === obj2)
{
alert('true');
}
else
{
alert('False');
}
});Why if(obj1 == obj2) returns false eventhough obj1 and obj2 are objects of same type?
-
Because the comparison is to see if they are references to the same object. And as you see they are two different objects.
-
OK, but then why then does this return True?
var obj1 = 2;
var obj2 = 2;
if(obj1 === obj2){
alert('true');
} else {
alert('False');
}It's the same code but for assigning an integer to the obj variables rather than an empty JSON string.