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.
The syntax for using the delete
operator is as follows:
delete object.property;
// OR
delete object["property"];
object
: This is the object whose property we want to delete.
property
: This is the property to be deleted.
The delete
operator returns true
if the specified property is deleted, or false
if the property is not deleted.
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 deleteconsole.log(delete human["country"]) // same as human.countryconsole.log(delete dog.country) // same as dog["country"]// log affected objectsconsole.log(human) // "country" property deletedconsole.log(dog) // "country" property deleted
When an object property does not exist, true
is returned without affecting the object, as shown below:
// creat objectlet human = {name: "John Doe",age: 15,country: "Nigeria"}// log value retured after deleteconsole.log(delete human.hobby); // returns "true"// log object to see if unaffectedconsole.log(human)