Everyone complaining about all the non-programming topics on HN, upvote this article, because it is the real deal. A deep, deep dive into a little-known technical aspect of a language many of us use every day.
Very comprehensive article, but if you have to delete properties, you're almost certainly coding wrong. Set the property to false, or null, or a null object.
Deleting properties also messes with the psuedo-class optimizations in V8.
First of all, thanks for kind words. I'm glad you found this post useful.
I think I should have given more attention to use cases of `delete` before delving into all the details of how it works :) My bad.
I wouldn't say using `delete` is almost always the wrong approach, but it is certainly often misunderstood. There are valid use cases where one needs to delete a property, usually before iterating over an object (and performing some operation on each of the remaining properties), or when using `in` operator to detect property existence. Note that simply assigning `undefined` doesn't delete property — it is still visible during iteration or when inspecting object with `in`/`Object#hasOwnProperty`.
In Prototype.js, there are also a couple of places where we use `delete` (such as to delete a property from an object for some special purpose (take care of IE bug) and then iterate over the remaining properties of an object — http://github.com/sstephenson/prototype/blob/master/src/dom/...)
The idea was to explain what can and can not be deleted; that deleting variables is useless (and even not future-compatible), unless those are declared from within eval (very unlikely); that deleting host objects is dangerous.
Everything else — i.e. deleting user-defined object properties — can and should be done in the right context ;)
Thanks for writing this post! You helped me understand more than just 'delete' - your explanation of the Global, Function and Eval contexts helped me understand closures better.
Actually, deleting items from array is usually done with `Array#splice`. Using `delete` operator only deletes a property, but doesn't update Array object's `length`, and it is this `length` that matters when iterating over an array (with `for(;;)`); when appending to array (using `Array#push`), and in few other cases.
In other words:
var array = [1,2,3,4];
delete array[2];
array.length === 4; // length is still 4
array.join() === '1,2,,4'; // which can lead to these kind of unexpected results
Thanks for writing such a detailed, informative post! For me it comes right on the heels of reading Crockford's Javascript: The Good Parts, which made me realize just how badly I was using JS.