How do I remove a property from a JavaScript object?

How do I remove a property from a JavaScript object?

To remove a property from a JavaScript object, you can use the delete operator. For example:

let obj = {
  foo: 'bar',
  baz: 42
};

delete obj.foo;

console.log(obj); // { baz: 42 }

This will remove the foo property from the obj object.

Alternatively, you can also use the Object.defineProperty() method to change the value of a property's configurable attribute to true, and then use the delete operator to remove the property. For example:

let obj = {
  foo: 'bar',
  baz: 42
};

Object.defineProperty(obj, 'foo', { configurable: true });
delete obj.foo;

console.log(obj); // { baz: 42 }

Keep in mind that the delete operator only works on own properties (properties that are directly present on an object, not inherited from its prototype). It cannot delete inherited properties or properties that have the configurable attribute set to false.


✋If you have any questions about this article, ask them in our GitHub Discussions 👈 community. You can also Gitter

❤️ Like our page and subscribe to our feed for updates!

Find a list of emojis to copy and paste