Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Objects Deep Dive: Deleting Object Properties With The delete Operator

Monday, October 18, 2021

JavaScript Objects Deep Dive: Deleting Object Properties With The delete Operator

In JavaScript you can delete an object's property with the delete operator.  Let's use the product object again as an example.

Let say you have the following JavaScript code to create a product object.


        var product = new Object();

        product.name = "Chai";
        product.category = "Tea";
        product.country = "India";
        product.badProperty = "Bad Property";
        product.badProperty2 = "Bad Property 2";
        product.supplier = {
            name: "ACME Tea Of India",
            location: "New Delhi"
        };

console.log(product);



If you view the above code in a web browser window you will see the following.












We are going to use the delete operator to delete badProperty and badProperty2.  As with the way we access properties we can delete properties with either the dot notation or the [] operator.  To delete the properties type in the following.

delete product.badProperty;
delete product["badProperty2"];

If you type console.log(product) again the two properties will no longer be there















No comments:

Post a Comment

Search This Blog