How to remove a property from a JavaScript?

Asked 19-Jul-2021
Updated 07-Jun-2023
Viewed 657 times

2 Answers


0

In JavaScript, you can remove a property from an object using the delete operator. Here's how you can do it:

var obj = { property1: "value1", property2: "value2", }; // Remove a property delete obj.property1; // Check if the property is removed console.log(obj.property1); // Output: undefined

In the above example, we have an object obj with two properties property1 and property2. To remove property1, we use the delete operator followed by the object name and the property name (delete obj.property1).

After removing the property, if you try to access it, it will return undefined, as demonstrated by console.log(obj.property1).

Note that the delete the operator removes the property from the object directly. If the property is inherited from a prototype chain, it will not affect the original prototype object.

To know with better understanding, you can join the Java training in Indore, Delhi, Meerut, Noida, Lucknow, Jaipur, Bhopal, Mumbai and other cities in India, choose your nearby location which is acceptable to you.


0

delete operator removes a property from an object in javascript, its single operand property must be an access expression, deletes the value of not only the property but also the value.

  1. The delete keyword removes a property from an object.
  2. The delete keyword deletes both the property's value and the property itself.
  3. After deletion, the property cannot be used before adding it back again.
  4. It has no effect on the variable or function.

Syntax

delete object-name.property-name

Example 

<!DOCTYPE html>

<html>
<body>
<h2>JavaScript Object Properties</h2>
<h1 id='hh'></h1>
<h2 style='color :red'>after deleting the age property from an object</h2>
<p id='demo'></p>
<script>
var person = {
  firstname: 'John',
  lastname: 'Doe',
  age: 50,
  eyecolor: 'blue'
};
document.getElementById('hh').innerHTML =person.firstname + ' is ' + person.age + ' years old.';
delete person.age;
document.getElementById('demo').innerHTML =
person.firstname + ' is ' + person.age + ' years old.';
</script>
</body>
</html>

Output 

JavaScript Object Properties

John is 50 years old.

after deleting the age property from an object

John is undefined years old.