Delete properties in JavaScript object

 Delete properties in JavaScript object

We already know that we can change the values that the object holds. But, we can completely delete/remove a property that's contained in the object.

In JavaScript, we use the delete operator to achieve this. This removes both the property and value itself. The properties deleted are eventually released automatically.

If you just want to delete the whole property i.e. key-value pair, set the value to undefined for performance.

If the property is removed it returns a Boolean true otherwise false

Syntax:
delete object.property or delete object['property']
 
Let's understand this with a simple example.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete a property from Object</title>
</head>
<body>
    <div id="res"></div>
    <script>
        var res = document.getElementById("res");

        var myDog = {
            name: "Fido",
            age: 5,
            breed: "Pug",
            favFood: "Muffins"
        };
        
        res.innerHTML = myDog.age;
        delete myDog.age;
        res.innerHTML += "<br>" + myDog.age;
    </script>
</body>
</html>



Post a Comment

0 Comments

React