Remove Property From Object In JavaScript

Remove Property From Object In JavaScript | In JavaScript, removing a property from an object can be done using two methods: the delete operator and the Object.defineProperty() method.

Remove Property From Object In JavaScript Using Delete Operator

The delete operator: The delete operator is a simple and straightforward way to remove a property from an object in JavaScript. The operator takes an object and a property as its operands, and it deletes the specified property from the object. Here’s an example:-

let obj = { name: "John", age: 30 };
delete obj.age;
console.log(obj);

Output:-

{ name: ‘John’ }

In the example above, the delete operator is used to remove the “age” property from the object “obj”. After the property is removed, the object only contains the “name” property. Also see:- How to Add New Property To Object in JavaScript

Using Object.defineProperty() method

Another method to remove a property from an object in JavaScript is the Object.defineProperty() method. This method allows you to define or modify the properties of an object. To remove a property, you can set the “configurable” property to true.

let obj = { name: "John", age: 30 };
Object.defineProperty(obj, "age", {
  configurable: true,
});
delete obj.age;
console.log(obj);

Output:-

{ name: ‘John’ }

When we set the “configurable” property to false, then it makes the property non-configurable and therefore, non-deletable. Here’s an example:-

let obj = { name: "John", age: 30 };
Object.defineProperty(obj, "age", {
  configurable: false,
});
delete obj.age;
console.log(obj);

Output:-

{ name: ‘John’, age: 30 }

In the example above, the Object.defineProperty() method is used to set the “configurable” property of the “age” property to false. As a result, the “age” property cannot be deleted using the delete operator, and the object still contains the “age” property after the delete operator is used.

In conclusion, removing a property from an object in JavaScript can be done using two methods: the delete operator and the Object.defineProperty() method. The delete operator is a simple and straightforward method to remove a property, while the Object.defineProperty() method allows you to control the properties of an object, including making them non-deletable. Choose the method that best fits your needs and use it in your JavaScript code to ensure that you have the right information when making decisions.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *