Alberto De Caro
Alberto De Caro

Reputation: 5213

JSON literals and Javascript objects. I am confused

Let's consider this code:

var a = {"id": "1", "name": "mike", "lastname": "ross"};
var b = JSON.parse('{"id": "1", "name": "mike", "lastname": "ross"}');
var c = Object.create({"id": "1", "name": "mike", "lastname": "ross"});

console.log(typeof a);
console.log(typeof b);
console.log(typeof c);

Questions

  1. Which are the differences between the three assignments?
  2. Do the objects a, b and c exactly overlap?
  3. If yes, why? If no, why?

Please add references to your answers.

Demo.

Upvotes: 7

Views: 386

Answers (2)

James Allardice
James Allardice

Reputation: 165941

a and b are effectively identical (they have the same properties, with the same values, in the same places). c is completely different. You can see a clear difference if you log the objects to the console instead of printing limited info to the page:

enter image description here

c is the one on the right. It's created an object with no own properties. The properties you specified are actually on the prototype of c. The reason for this is that the first argument to Object.create is the prototype of the object to be created.

Note that you could use Object.create to get the same effect - just pass Object.prototype as the first argument:

var d = Object.create(Object.prototype, { 
    "id": { "value": 1 }, //values are 'property descriptors'
    "name": { "value": "mike" }
    //etc...
});

Upvotes: 6

Rob W
Rob W

Reputation: 348972

a and b result in "indentical" objects (in the same way that {a:1} abd {a:1} are identical).

JSON.parse parses the input JSON string, and outputs the parsed value. In this case, an object.

c is different. Object.create creates a new object with the prototype set to the first argument. You can verify that c.__proto__.id is equal to 1 (and unavailable in the first two cases).

At the first sight, all of the three methods result in the "same" object: Reading the property id gives 1 in all cases. In the third case, this result is caused by prototype inheritance. This offers a possible feature:

var x = Object.create({id:1});
x.id = NaN;
console.log(x.id);
// NaN
delete x.id;
console.log(x.id);
// 1 - The old value is back :)
// ( for x = {id: 1};, the old value would be gone! )

Upvotes: 6

Related Questions