Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I remove a property from a JavaScript object?
To remove a property from a JavaScript object, use the delete keyword. The delete operator removes a property from an object and returns true if the deletion was successful.
Using the delete Operator
The delete operator is the most common way to remove properties from JavaScript objects. Here's the basic syntax −
delete objectName.propertyName; // or delete objectName['propertyName'];
Example
You can try to run the following code to learn how to remove a property −
var cricketer = {
name: "Amit",
rank: 1,
points: 150
};
console.log("Before deletion:", cricketer);
delete cricketer.rank;
console.log("After deletion:", cricketer);
// Trying to access deleted property
console.log("Rank value:", cricketer.rank); // undefined
The output of the above code is −
Before deletion: {name: "Amit", rank: 1, points: 150}
After deletion: {name: "Amit", points: 150}
Rank value: undefined
Complete HTML Example
Here's a complete HTML example demonstrating property deletion −
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cricketer = {
name: "Amit",
rank: 1,
points: 150
};
delete cricketer.rank;
document.getElementById("demo").innerHTML =
cricketer.name + " has " + cricketer.rank + " rank.";
</script>
</body>
</html>
The output of the above code is −
Amit has undefined rank.
The delete operator successfully removes the specified property from the object, and accessing the deleted property returns undefined.
Advertisements
