Explain Codes LogoExplain Codes Logo

How do I remove a property from a JavaScript object?

javascript
delete-operator
object-destructuring
array-manipulation
Alex KataevbyAlex Kataev·Aug 14, 2024
TLDR

Easily remove an object property in JavaScript with the delete operator. For instance, to strike off the regex field from myObject:

delete myObject.regex; // 'yup, regex is now toast in 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:

  1. Dot notation: A clean approach, commonly preferred when the property name is a valid identifier and known before runtime.
delete myObject.regex; // It's like regex never existed
  1. Bracket notation: A vital method when the property name is dynamic or not a valid identifier - may even be stored in a variable.
delete myObject['regex-pattern']; // For invalid identifiers let prop = 'regex'; delete myObject[prop]; // Gotcha! You can't hide from deletion

Immutable property deletion: Destructuring

To maintain the original object's sanctity, you use object destructuring for immutable operations:

const { regex, ...newObject } = myObject; // Regex is too mainstream, excluded!

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:

Object.defineProperty(myObject, 'constant', { value: 123, configurable: false }); delete myObject.constant; // Returns false, property is like "You can't get rid of me!"

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:

let ghost = myObject.regex; delete myObject.regex; // Ghost: "Who you gonna call now?" 🚫👻

Deleting array properties

Using delete for array elements is like moving out of your house and leaving behind an empty room:

let myArray = ['a', 'b', 'c']; delete myArray[1]; // 'b' is gone, but myArray's length remains the same, leaving an 'empty room'

To avoid such a mess, consider using the splice method:

myArray.splice(1, 1); // 'b' gets kicked out with its 'room'

Caveats and considerations

Verifying deletion

To check whether the property received its eviction notice:

console.log('regex' in myObject); // False if evicted, true if not

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!