To delete a key from an object in JavaScript, you can use the delete
operator.
There are the following two ways you can delete a key from an object using the delete
operator:
delete object['keyname'] or delete object.keyname
For example, let’s say we have a person object which contains three keys, name
, age
, and gender
of the person. And we want to remove the name
key from this person object.
let person = { name: 'John', age: 24, gender: 'Male' }; delete person['name']; // Remove the 'name' key from person object // OR delete person.name // Also removes the 'name' key from person object
What if the key doesn’t exist?
If the key to be removed doesn’t exist, the delete
operator does nothing. That is, the object remains as it is and no error is thrown by the JavaScript compiler.