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

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

<!DOCTYPE html>
<html lang="en">
    <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>
    <div id="res"></div>
        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;

Post a Comment