How do I remove a property from a JavaScript object?
Easily remove an object property in JavaScript with the delete operator. For instance, to strike off the regex field from myObject:
A quick glance might heed you to use the delete operator all the time, but there are alternative techniques and significant notes explored below.
Different ways to delete properties
delete operator with different notations
Two syntactic variants of the delete operator exist for your convenience:
- Dot notation: A clean approach, commonly preferred when the property name is a valid identifier and known before runtime.
- Bracket notation: A vital method when the property name is dynamic or not a valid identifier - may even be stored in a variable.
Immutable property deletion: Destructuring
To maintain the original object's sanctity, you use object destructuring for immutable operations:
This extracts the regex property into its constant and newObject gets the remaining properties.
An exception: Non-configurable properties
Trying to delete non-configurable properties, defined with { configurable: false }, is like trying to sprint in a dream – you simply can’t:
delete and memory management
On deleting a property, its memory space can now sing "I will survive", ready to be reclaimed, once all references are gone:
Deleting array properties
Using delete for array elements is like moving out of your house and leaving behind an empty room:
To avoid such a mess, consider using the splice method:
Caveats and considerations
Verifying deletion
To check whether the property received its eviction notice:
Empty slots in array iteration
Array methods like forEach, map, and reduce will strut past empty slots caused by delete. So, you might have some unexpected party guests in your iteration logic.
Cross-browser compatibility
The delete operator is popular among browsers. Firefox, Chrome or IE, it doesn't matter – it just deletes everywhere!
Was this article helpful?