¿Por qué dos objetos idénticos no son iguales entre sí?

Seems like the following code should return a true, but it returns false.

var a = {};
var b = {};

console.log(a==b); //returns false
console.log(a===b); //returns false

¿Cómo esto tiene sentido?

preguntado el 28 de julio de 12 a las 22:07

Yea, it is pretty much the same question. -

You are trying to compare two objects. js objects returns true only when both point to the same memory location. So if you want to compare, whether the CONTENT of the objects are same. You have to first convert them to string like JSON.stringify(a) == JSON.stringify(b) -

9 Respuestas

The only difference between regular (==) and strict (===) equality is that the strict equality operator disables type conversion. Since you're already comparing two variables of the same type, the kind of equality operator you use doesn't matter.

Regardless of whether you use regular or strict equality, object comparisons only evaluate to true if you compare the same exact object.

Es decir, dado var a = {}, b = a, c = {};, a == a, a == b, pero a != c.

Two different objects (even if they both have zero or the same exact properties) will never compare equally. If you need to compare the equality of two object's properties, this question has very helpful answers.

contestado el 23 de mayo de 17 a las 13:05

Utilice underscorejs.js isEqual para comparar objetos JSON underscorejs.org/#isEqual - Remo H. Jansen

use JSON.stringify(objname);

var a = {name : "name1"};
var b = {name : "name1"};

var c = JSON.stringify(a);
var d = JSON.stringify(b);


Respondido el 24 de junio de 16 a las 08:06

Here is a quick explanation of why {} === {} devoluciones false en JavaScript:

From MDN Web Docs - Working with objects: Comparing objects.

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

// Two variables, two distinct objects with the same properties
var fruit = {name: 'apple'};
var fruitbear = {name: 'apple'};

fruit == fruitbear; // return false
fruit === fruitbear; // return false
// Two variables, a single object
var fruit = {name: 'apple'};
var fruitbear = fruit;  // Assign fruit object reference to fruitbear

// Here fruit and fruitbear are pointing to same object
fruit == fruitbear; // return true
fruit === fruitbear; // return true

fruit.name = 'grape';
console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" }

For more information about comparison operators, see Operadores de comparación.

Respondido 03 Jul 20, 20:07

¿Cómo esto tiene sentido?

Because "equality" of object references, in terms of the == y === operators, is puramente based on whether the references refer to the mismo object. This is clearly laid out in the abstract equality comparison algorithm (usado por ==) y el algoritmo de comparación de igualdad estricta (usado por ===).

En tu código, cuando dices a==b or a===b, you're not comparing the objetos, you're comparing the references in a y b to see if they refer to the same object. This is just how JavaScript is defined, and in line with how equality operators in many (but not all) other languages are defined (Java, C# [unless the operator is overridden, as es para string], and C++ for instance).

JavaScript has no inbuilt concept of equivalencia, a comparison between objects that indicates whether they're equivalent (e.g., have the same properties with the same values, like Java's Object#equals). You can define one within your own codebase, but there's nothing intrinsic that defines it.

Respondido el 01 de diciembre de 15 a las 16:12

As from The Definitive Guide to Javascript.

Objects are not compared by value: two objects are not equal even if they have the same properties and values. This is true of arrays too: even if they have the same values in the same order.

var o = {x:1}, p = {x:1};  // Two objects with the same properties
o === p                    // => false: distinct objects are never equal 
var a = [], b = [];        // Two distinct, empty arrays 
a === b                    // => false: distinct arrays are never equal 

Objects are sometimes called reference types to distinguish them from JavaScript’s primitive types. Using this terminology, object values are references, and we say that objects are compared by reference: two object values are the same if and only if they refer to the same underlying object.

var a = {};   // The variable a refers to an empty object. 
var b = a;    // Now b refers to the same object. 
b.property = 1;     // Mutate the object referred to by variable b. 
a.property          // => 1: the change is also visible through variable a. 
a === b       // => true: a and b refer to the same object, so they are equal. 

If we want to compare two distinct objects we must compare their properties.

Respondido el 04 de junio de 16 a las 22:06

Esta es una solución alternativa: Object.toJSON(obj1) == Object.toJSON(obj2)

By converting to string, comprasion will basically be in strings

Respondido 28 Jul 12, 23:07

The question was about the reason of the effect, an explanation of the observed, and not a “solution” to comparing two objects. - Kissaki

Given that the order of properties in a object is not guaranteed, this doesn't (always) work. You could end up with {a:1,b:2} != {b:2,a:1} even though they're the same. Additionally, objects with cyclic references don't translate to JSON. - josh3736

First, this doesn't answer the question. Second, there is no Object.toJSON defined in JavaScript. Third, assuming you meant JSON.stringify from ES5, you can't rely on it returning exactly the same string for two objects that have the same properties with the same values, because nowhere in the spec does it require that the properties (which are desordenado) be listed in the same order. The engine is free to do what it wants, which may vary depending on how the objects were constructed, even if they terminar with the same properties with the same values. - TJ Crowder

True, I have never thought of that because I always formulated objects with the same order of parameters. And yes, Kissaki, quite right, I just wanted to give an example how to solve it. - anze jarni

@AnzeJarni: "...I always formulated objects with the same order of parameters..." Assuming you meant properties, again, object properties no tengo orden. Although granted, if you create an object and add a, b y c properties to it; then create another object and add a, b y c properties to it, it would be a very strange engine indeed that serialized those to JSON differently. But if you made the second object by adding c, b, y entonces a to it, that wouldn't necessarily be strange at all. - TJ Crowder

¿Cómo esto tiene sentido?

Imagine these two objects:

var a = { someVar: 5 }
var b = { another: 'hi' }

Ahora si lo hicieras a === b, you would intuitively think it should be false (which is correct). But do you think it is false because the objects contain different keys, or because they are diferentes objetos? Next imagine removing the keys from each object:

delete a.someVar
delete b.another

Both are now empty objects, but the equality check will still be exactly the same, because you are still comparing whether or not a y b are the same object (not whether they contain the same keys and values).

contestado el 07 de mayo de 18 a las 13:05

===, la estrictamente igual operator for objects checks for identity.

Dos objetos son estrictamente iguales si se refieren al mismo Objeto.

Those are two different objects, so they differ.

Think of two empty pages of paper. Their attributes are the same, yet they are not the same thing. If you write something on one of them, the other wouldn't change.

Respondido 28 Jul 12, 23:07

And should you still want to check for equality, use the .equals() method on objects - Wouter

The regular equality operator works the same way. The only difference is whether type conversion is allowed, which doesn't matter in this case. - josh3736

@josh3736: yes. and you should almost never use ==. - karoly horvath

In Javascript each object is unique hence `{} == {}` or `{} === {}` returns false. In other words Javascript compares objects by identity, not by value.

 1. Double equal to `( == )` Ex: `'1' == 1` returns true because type is excluded 
 2. Triple equal to `( === )` Ex: `'1' === 1` returns false compares strictly, checks for type even

Respondido 14 Jul 20, 08:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.