2

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 
2
  • You have to write an object comparer, because it is comparing the pointers. the only way the above would work is a = {same:'same'}; b=a; a===b; ->true Commented Apr 3, 2014 at 5:12
  • 2
    Read the standard. The algorithm for == is in 11.9.3, the one for === is in 11.9.6. They both say, among other things, "Return true if x and y refer to the same object. Otherwise, return false." Commented Apr 3, 2014 at 5:14

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

care to explain a bit more in detail
@WebDeveloper - There's not that much to explain, this is how it's defined and implented, there's really no long explanations as to why it is that way, it just is.
1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.