I am trying to remove a property from an Person object like this:
const Person = {
firstname: 'John',
lastname: 'Doe'
}
console.log(Person.firstname);
// Output: "John"
delete Person.firstname;
console.log(Person.firstname);
// Output: undefined
When I am using this delete operator is working fine and Person.firstname log is showing as undefined as expected. But when I create a new object using this Person object using Object.create() method like this:
const Person = {
firstname: 'John',
lastname: 'Doe'
}
const Person2 = Object.create(Person);
console.log(Person2.firstname);
// Output: "John"
delete Person2.firstname;
console.log(Person2.firstname);
// expected output: undefined
// actual output: "John"
You can see Person2.firstname is returning "John" in the end, when I was expecting it to work same way as done in the first snippet and return undefined.
So, my questions here are:
- Why is
delete Person2.firstnamenot working? - Also, how can we delete
firstnameproperty from thePerson2object?
Thanks for your help.
deletewill only successfully remove a property from an object if the property to be deleted is an own non-configurable property. Here, yourPerson2does not have an own property offirstname, sodelete Person2.firstnamedoesn't work. The property exists on the internal prototype ofPerson2, but not onPerson2itself.To delete the property, you'll have to call
deletewith the prototype object:or, if you don't already have a reference to it, use
Object.getPrototypeOf: