Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deleting the property from an object is not working

I have defined an object Employee with a property name company. After creating a new object Emp1 I tried to delete the property from the object but it still exists under the object Emp1. What is the reason for it?

var Employee = {
  company: 'xyz'
}
var Emp1 = Object.create(Employee);
delete Emp1.company;
console.log(Emp1.company);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are using Object.create to create an object Emp1 with the object that has the property Employee* as its prototype. So the property is not a part of your Emp1, its part of the prototype object Employee and thus deleting it on Emp1 has no effect.

Try it out yourself: If you added the property to your Emp1 object it would exist until you deleted it:

let Employee = {company: 'xyz'};
let Emp1 = Object.create(Employee);
Emp1.company = 'Emp1s company';
console.log(Emp1.company); // -> 'Emp1s company' (property from Emp1)
delete Emp1.company;
console.log(Emp1.company) // -> 'xyz' (the value from the prototype)

This is how prototypical inheritance works in JS. A property shadows the same prototype property as long as it exist, if you remove it you get the same property from the prototype if it exists (if not from the prototypes prototype etc.)

(So Object.create is not making a copy – it’s creating an object with another object as its prototype.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading