Unlikely other languages JavaScript allows you to delete properties as well. So consider following object


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

Suppose you want to delete grade property. You can do that as following,


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

Some important points about delete operator is as follows,

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

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

image

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

alert(delete (student.subject));

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

image

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

alert(delete (student));

When you execute above code you will get false as return of delete operation.

image

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

Advertisements

3 thoughts on “Deleting Properties of JavaScript object

  1. After I initially left a comment I seem to have clicked
    on the -Notify me when new comments are added- checkbox and from now on each
    time a comment is added I receive four emails with the same comment.

    Is there a way you can remove me from that service?
    Appreciate it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s