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"}
2
  • possible duplicate of How to determine equality for two JavaScript Objects? Commented Aug 5, 2014 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. Commented Aug 5, 2014 at 15:17

3 Answers 3

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).

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

Comments

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

1 Comment

Don't use the first method, nothing guarantee the order of your object properties.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.