0

Can anyone help me to understand the difference in obj1 and obj2 created in two ways in JavaScript? They look the same in the console.

var obj1 = { 'name': 'blue', 'shade': 'dark'};
var obj2 = JSON.parse('{"name":"blue","shade":"dark"}');

because

 (obj1 === obj2)  is false as 
 (obj1 == obj2) is false

while in javascript console show as

Object {name: "blue", shade: "dark"}
Object {name: "blue", shade: "dark"}
Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
HYA
  • 41
  • 4
  • possible duplicate of [How to determine equality for two JavaScript Objects?](http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – Getz Aug 05 '14 at 15:14
  • A variable that is assigned an object doesn't actually hold the value of the object, but rather a reference to it. 2 separate objects, 2 different references. – Elias Van Ootegem Aug 05 '14 at 15:17

3 Answers3

3

While the objects content is the same, you have references to two separate objects, which is why == and === both fail (they check for reference not content).

ABucin
  • 936
  • 1
  • 7
  • 18
1

As ABucin said, javascript checks for references, if you still want to check if two jsons are equal you could try using

JSON.stringify(obj1) === JSON.stringify(obj2)

or check for every key (a bit more complicated but more efficient in the case that the keys are in different orders).

Try reading this:

Compare 2 json objects

Community
  • 1
  • 1
Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72
0

you are creating an object with obj1 and in obj2 you parsing a JSON object into an object. Since both objects are different (different reference) they are treated as different

You can learn more on this over here

V31
  • 7,626
  • 3
  • 26
  • 44