The “Delete” Keyword in JavaScript

Ever used it? Well, before today, I hadn’t!

Basically, if you’ve got an object, and you’re wanting to completely remove a property that it has (not just set it to “null” or “undefined”), you use this keyword!

Say you’ve got:

myObject = {prop1: “blah”, prop2: “blah”}

And you want to remove “prop2” — not just remove it’s value; remove it completely from the object. This is important when returning values to the server — just the presence of a property name even without a corresponding value can cause problems.

So, what do you do? Well, you can loop through the property with a “for (property in object)” loop, leaving out the one you don’t want, or you can just “delete” it:

delete myObject.prop2

And that’s it. Now, if you turn “myObject” into JSON or whatever, all you’ll have is:

myObject = {prop1: “blah”}

And that’s that. I’ll be on vacation for the next two weeks, so don’t worry about the absence!

Yes, all six of you, don’t worry. :P

5 thoughts on “The “Delete” Keyword in JavaScript”

  1. I always wondered why assigning undefined doesn't just delete automatically. This is one of those quirks that everyone will run into eventually=).

    Thanks for the post.

Leave a Reply