Today I stumbled upon a question here on Stack Overflow – How do I remove objects from a javascript associative array?. What struck me was that the accepted answer was both misleading and heavily upvoted, so I highlighted the possible pitfall.
However, while cobbling together a corrective answer, I realized I have no idea as to why it makes sense for delete to keep elements assign undefined instead of removal.
var elements = new Array()
elements.push(NaN)
elements.push(NaN)
elements.push(NaN)
delete elements[1]
console.log("number of elements: ", elements.length) // returns 3
Is there a rationale behind it?
It doesn’t.
deleteremoves properties from objects, it does not set them toundefined. Here’s an easy way to tell:Note that after the
delete,adoesn’t have a property called1anymore. At all.Contrast with:
There,
astill has a property called1, it’s just that the property’s value isundefined.It’s useful to understand that in JavaScript, arrays aren’t really arrays at all. They’re just objects, array “indexes” are just property names (which are strings — yes, really, we just tend to write them as numbers), arrays have special handling of property names that are all numeric (indexes), a special
lengthproperty, and some functions they get fromArray.prototype. This is very clearly laid out in Section 15.4 of the spec. Once you have it set firmly in your head that JavaScript arrays aren’t really arrays, they make a lot more sense. 🙂Deleting an array “index” property from an array does not change its
length(not even if you delete the highest-numbered one); it just creates a hole in the array (JavaScript “arrays” are sparse arrays by their nature; e.g., they can have gaps in them). So in my first example above, I get exactly the same array that I’d’ve gotten if I’d done this:Note the gap, the array has no
1element/property.If you say:
…
foocan get the valueundefinedfor two completely different reasons:ahas a property called3that has the valueundefined, or:ahas no property called3at all; the result of a property accessor operation on an object that doesn’t have a property by that name isundefined. This if-no-property-return-undefinedis covered by the spec in a fairly convoluted way, but mostly in Section 8.12.3.These are very distinct things.