Quick Tip – Deleting a JavaScript Object Property

March 21, 2012

no comments

Quick Tip – Deleting a JavaScript Object Property

Lately, I’m writing a JavaScript library which I’ll publish and write about in the near future. On the meanwhile, during the development I had to delete a property on a JavaScript object that I’ve created. Since JavaScript is a dynamic language that operation is available and is achieved through the delete operator. This post will describe the JavaScript delete operator and how to use it.

The JavaScript Delete Operator

The delete operator is used to delete properties that were declared implicitly on a JavaScript object. If the properties are declared with the var keyword or function statement the delete operator won’t work. Also, properties that are declared on the object’s prototype can only be deleted on the prototype and not from the inheriting object.

Simple Example

In the example I’ll use the following JavaScript object:

var obj = {};

obj["key"] = "value";

In the following lines of code, each line can be used to the delete the previously created key property:

delete obj["key"];
delete obj.key;

The delete operator can also be used with JavaScript arrays in order to remove an item. Here is an example for that:

var arr = ["item1", "item2", "item3", "item4"];
delete arr[2];
console.log(arr.length); // will print 4
console.log(arr[0]); // will print item1
console.log(arr[1]); // will print item2
console.log(arr[2]); // will print undefined
console.log(arr[3]); // will print item4

The delete operator does nothing if it is used on a non property item. 

Summary

Lets sum up, the post explained what is the JavaScript delete operator and how to use it. In most cases you will not use this operator but when creating JavaScript libraries it is very handy.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*