javascriptobjectjavascript-objects

Why does `new Object()` not compare equal to an empty object literal, `{}`?


I have the following code:

var a = new Object();
var b = {};
console.log(a == b || a === b);

and it prints false. What is the reason behind this?


Solution

  • When you compare the equality of objects you compare whether the two objects have the same instance (meaning that the variables you compare do reference the same memory).

    You have two different instances, so equality comparison yields false.

    If you want to check if all properties of two objects have equal values it is a different thing and you really have to check equality for each object property.