Deleting Properties of JavaScript Object

It is unlikely that languages other than JavaScript allow you to delete properties as well. 

Before reading this article, you may want to go through the following articles:

So consider the following object:

var student =
                {
                    name:
"dj",
                    grade: 10
                };

Suppose you want to delete the grade property. You can do that with the following:

delete student.grade;
delete student["grade"];

Some important points about the delete operator is as follows:

  1. It deletes the object's own property
  2. It does not delete an inherited property. For example you cannot delete a property of the student prototype or the object it is inheriting from.

The delete operator returns true on success and if there is no effect of the delete operation.

Object1.jpg

For example in the above object there is no property with identifier subject and you try the following code:

alert(delete (student.subject));

Since the above delete operator is doing nothing, it is returning true and you will get true as output in the alert.

Object2.jpg

Now consider another scenario to understand when the delete operator cannot perform a delete operation. Suppose a student object is defined globally and you try to delete that as follows. You cannot delete this.

alert(delete (student));

When you execute the code above the delete operation will return false.

Object3.jpg

In this way you can work with the delete operator and deletion of object properties. I hope you find this article useful. Thanks for reading.
 

Up Next
    Ebook Download
    View all
    Learn
    View all