If Object.create makes new deep copy of the object, what should happen post deleting the property from the newly created object?
Expected Output: Undefined
Actual Output: Karna
Code
var obj1 = {name:"Karna",loc:"Bengaluru"};
var obj2 = Object.create(obj1);
delete obj2.name;
console.log(obj2.name);
Could you please help me to understand why obj2.name still referring to obj1's property?
Object.create creates a new object with the argument object as prototype of the new object created (refer to the __proto__ of the newly created object). It does not add the properties of obj1 to obj2. So, if you invoke delete on obj2, it will delete the properties of obj2, and not the ones in the prototype.
Example:
var obj1 = { name: 'John' }
var obj2 = Object.create(obj1);
console.log(obj2.__proto__ === obj1) // returns true
console.log(obj2.hasOwnProperty('name')) // returns false;
console.log(obj2.name) // returns John
delete obj2.name; // returns true
console.log(obj2.name) // returns John, since delete will not traverse the prototype chain to delete keys
More info : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
There two points you should pay atention:
1- Object.create doesn't make copy of original object, it creates a new object with the argument object as prototype of the new object created. (prototype property is not configurable property)
2- delete operator just works on configurable properties of an object.
so, prototype properties are not deletable by delete operator, because they're not configurable.