How to remove a property from an object in JavaScript

published: 18 Sep 2022

2 min read

How to remove a property from an object in JavaScript

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
delete foods.pizza;

// OR

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

console.log(foods);
// { 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.

How to remove a property from an object in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming