How to Remove a Property from a JavaScript Object
Deleting a property from a JavaScript object can be done using the delete
keyword. Alternatively, you can set the property to undefined
. This article discusses these options and provides a suggested solution.
The most semantically correct way to remove a property from an object is to use the delete
keyword. For example, given the object:
1 | const car = { |
You can delete a property from this object by using:
1 | delete car.brand |
The delete
keyword can also be expressed as:
1 | delete car['brand'] |
Another option to remove a property is to set it to undefined
. While this option can improve performance, especially when operating on a large number of objects in loops, it is important to note that the property is not actually deleted from the object. Its value is simply wiped. For example:
However, if mutability is a concern, and you want to completely remove the property without mutating the original object, you can create a new object by copying all properties from the old object, except the one you want to remove. This can be achieved using Object.keys()
:
1 | const car = { |
Tags: JavaScript, object manipulation, delete property, undefined, mutability, immutability