In an earlier article, we looked at how to add a property to an object in JavaScript. But what if you want to remove a specific property from an object?

JavaScript provides the delete operator to remove a property from an object. On successful deletion, it will return true, otherwise false:

const foods = { burger: '🍔', pizza: '🍕', cake: '🍰' };

// Dot Notatation

// OR

// Square Bracket Notation
delete foods['pizza'];

// { burger: '🍔', cake: '🍰' }

The delete operator works with both dot notation (.) as well as square bracket ([]) notation.

When using the delete operator, you should consider the following scenarios:

  • If the property which you are trying to delete does not exist, delete will do nothing and will simply return true.
  • If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain. In other words, delete only removes properties from the object's own properties and has no effect on the object's prototype properties.
  • Any property declared with let or const cannot be deleted from the scope within which they were defined.

Take a look at this MDN article to learn more about the delete operator in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.