Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object and primitive type equality

I know that identical objects are not equal, i.e:

var obj = { name: "Value" };
var obj2 = { name: "Value" };

console.log("obj equals obj2: " + (obj === obj2)); //evaluates to false

Yet primitive types are:

var str = "string1";
var str2 = "string1";

console.log("str equals str2: " + (str === str2)); //evaluates to true

My question is why. Why are objects and primitives treated differently? If an object is nothing but an empty container, with only the attributes you specify to put in the container, why wouldn't the container's identical attributes evaluate to be the same? I looked around for this answer on SO and elsewhere, but didn't find an answer.

Is a JS object treated as something different in the DOM than a primitive type?

Thanks

like image 628
user3871 Avatar asked Nov 25 '25 14:11

user3871


2 Answers

This seems to really be a question about === so let's look at the Strict Equality Comparison Algorithm, in which point 7 says

Return true if x and y refer to the same object. Otherwise, return false.

So what does it mean to be "the same object"? It means they don't just look like eachother, but are at the same place in memory too. This means that the only time when an Object is === to an Object is when they're the same thing.

var a = {},
    b = {}, // identical to `a`
    c = a;  // same as `a`
a === b; // false
a === c; // true
b === c; // false
like image 142
Paul S. Avatar answered Nov 28 '25 02:11

Paul S.


When a variable's value is an object, well, it isn't an object: it's a reference to an object. Two variables that contain references to the same object are indeed equal:

var myObj = { hello: "world" };
var a = myObj;
var b = myObj;

if (a == b) alert("YES!!"); // YES!!

When the == operator has object references on both sides, the comparison made is to test whether the objects refer to the same object. When primitive values are involved, the semantics are different: the values are directly compared.

like image 42
Pointy Avatar answered Nov 28 '25 03:11

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!