What is the delete operator in JavaScript?

The delete operator in JavaScript is used to delete an object’s property.

If it is used to delete an object property that already exists, it returns true and removes the property from the object. However, deleting an object property that doesn’t exist will not affect the object, but will still return true.

The only time false will be returned is when the delete operator is used to delete a variable or a function.

Syntax

The syntax for using the delete operator is as follows:

delete object.property;
// OR
delete object["property"];

Parameters

object: This is the object whose property we want to delete.

property: This is the property to be deleted.

Return value

The delete operator returns true if the specified property is deleted, or false if the property is not deleted.

Code

In the code below, an object is created and the delete operator is used to delete some of its properties:

let human = {
name: "John Doe",
age: 15,
country: "Nigeria"
}
let dog = {
name: "Buddy",
age: 2,
country : "Germany"
}
// log retured values after delete
console.log(delete human["country"]) // same as human.country
console.log(delete dog.country) // same as dog["country"]
// log affected objects
console.log(human) // "country" property deleted
console.log(dog) // "country" property deleted

When an object property does not exist, true is returned without affecting the object, as shown below:

// creat object
let human = {
name: "John Doe",
age: 15,
country: "Nigeria"
}
// log value retured after delete
console.log(delete human.hobby); // returns "true"
// log object to see if unaffected
console.log(human)

Free Resources