The JavaScript delete Operator

By

Learn how the JavaScript delete operator removes a property or method from an object, using either the dot notation or the square bracket syntax.

~~~

The delete JavaScript operator is used to delete a property from an object. Not the variable itself, not an array item you should remove properly, just object properties.

Say you have this object:

const car = {
  model: 'Fiesta',
  color: 'green'
}

You can delete any property from it, or method, using the delete operator:

delete car.model

console.log(car)
//{ color: 'green' }

You can also reference the property/method using the brackets syntax:

delete car['color']

The brackets syntax is what you reach for when the property name is in a variable:

const field = 'color'
delete car[field]

Note that delete works on a const object. We’re not reassigning the variable, we’re mutating the object it points to, and that’s allowed.

What does delete return?

delete returns true when the operation succeeds:

delete car.model //true

It also returns true when the property doesn’t exist at all. It only returns false (or throws, in strict mode) when the property exists but can’t be removed.

When does that happen? With non-configurable properties, for example on a frozen object:

'use strict'

const settings = Object.freeze({ theme: 'dark' })
delete settings.theme
//TypeError: Cannot delete property 'theme' of #<Object>

Modules and classes run in strict mode automatically, so in modern code expect the error, not a silent false.

What if you don’t want to mutate the object?

delete changes the object in place. Sometimes you’d rather keep the original and get a new object without the property. Rest destructuring does that:

const car = {
  model: 'Fiesta',
  color: 'green'
}

const { model, ...rest } = car

console.log(rest) //{ color: 'green' }
console.log(car) //unchanged

rest is a new object with every property except model.

Don’t use delete on arrays

Here’s the pitfall that bites people. delete technically works on array indexes, but it doesn’t do what you want:

const scores = [10, 20, 30]
delete scores[1]

console.log(scores) //[ 10, <1 empty item>, 30 ]
console.log(scores.length) //3

The item is gone, but the array keeps a hole in the middle, and length is still 3. Iterating this array now gives you undefined in position 1.

To actually remove an array item, use splice():

const scores = [10, 20, 30]
scores.splice(1, 1)

console.log(scores) //[ 10, 30 ]
console.log(scores.length) //2

splice(1, 1) removes one item starting at index 1, and the array shrinks like you’d expect.

~~~

Related posts about js: