How to Delete a Property of an Object in JavaScript


JavaScript provides a delete operator which is used to remove a property from an object; if no more references to the same property are held, it is eventually released automatically.

Let's demonstrates how to delete a property of an Object in Javascript with an example.

Example 1 - Delete a property from an object

 // using Object Literals
    var user = {
        firstName : 'Ramesh',
        lastName : 'Fadatare',
        emailId : 'ramesh@gmail.com',
        age : 29,
        getFullName : function (){
            return user.firstName + " " + user.lastName;
        }
    }
    
    function testDeleteOperator(){
    
        console.log("before delete user object properties -> " + JSON.stringify(user));
    
        // delete properties
        delete user.firstName;
        delete user.age;
    
        // delete functions
        delete user.getFullName();
    
        console.log("after delete user object properties -> " + JSON.stringify(user));
    }
    
    testDeleteOperator();
Output:
before delete user object properties -> {"firstName":"Ramesh","lastName":"Fadatare","emailId":"ramesh@gmail.com","age":29}
after delete user object properties -> {"lastName":"Fadatare","emailId":"ramesh@gmail.com"}

Example 2

The following snippet gives a simple example:
var Employee = {
  age: 28,
  name: 'abc',
  designation: 'developer'
}

console.log(delete Employee.name);   // returns true
console.log(delete Employee.age);    // returns true

// When trying to delete a property that does 
// not exist, true is returned 
console.log(delete Employee.salary); // returns true

Testing

For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.

You can refer below screenshot for your testing:

Comments