Question

I run the following in console why is the output false. Not asking how to compare two objects but why these two objects are not same.

> a = {same:'same'}
Object {same: "same"}
> b = {same:'same'}
Object {same: "same"}
> a === b
false
> a == b
false
Était-ce utile?

La solution

Two objects are never the same even if they have the same content, as two different instances of Object is never equal.

When comparing two object, JavaScript compares internal references which are equal only when both operands refer to the same object in memory, keys and values are not checked, so the content of the object doesn't matter, the operands both have to reference the same object to return true in a comparison.

Autres conseils

This is simply due to how == is defined per the The Abstract Equality Comparison Algorithm:

1. If Type(x) is the same as Type(y) [i.e. Type(x) == Type(y) == Object], then ..

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

None of the other rules/conversions apply because both operands are Objects.

Although there is no ECMAScript 5th edition "core" support for this task, several solutions are discussed in How to determine equality for two JavaScript objects?


This has naught to do with "references", which are an implementation detail not defined in ECMAScript, and can be entirely discussed per the above rules: two different Objects are never equal per == (and by extension ===) rules.

You are comparing two objects which never be equal. If you compare a.same and b.same then they will be the same.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top