Search code examples
javascriptjson

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.


Solution

  • 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...
    });