Is delete array[i] the same as array[i] = undefined? I know that the former will produce a sparse array? Does the latter do the same?
3 Answers
No, the latter does not do the same, it just sets that index to the value undefined, it does not delete that index.
delete will delete the index, but will not update the length, so you end up with an index that is truly not defined, and doesn't just contain the value undefined.
In other words, a "sparse" array where the length is greater than the number of items.
You can test this easily with most array methods, as they will iterate over the value undefined, but not over indexes that aren't defined (there's a difference)
var arr = [0, 1, 2, 3];
delete arr[1]; // delete the second index
arr.forEach(function(item) {
console.log(item); // 0, 2, 3
});
console.log('--------')
var arr2 = [0, 1, 2, 3];
arr2[1] = undefined; // set the second index to "undefined"
arr2.forEach(function(item) {
console.log(item); // 0, undefined, 2, 3
});
Comments
No, they don't do the same. From MDN's delete operator article:
Deleting array elements
When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.
When the
deleteoperator removes an array element, that element is no longer in the array. In the following example,trees[3]is removed withdelete.var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; delete trees[3]; if (3 in trees) { // this does not get executed }If you want an array element to exist but have an
undefinedvalue, use the undefined value instead of thedeleteoperator. In the following example,trees[3]is assigned the value undefined, but the array element still exists:var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees[3] = undefined; if (3 in trees) { // this gets executed }
Comments
By using both one can make a dense array sparse or not. Their usage is different.
Let's see...
var arr = [1,2,3];
delete arr[10]; // <- returns true but arr is not sparse
delete arr[1]; // <- returns true and arr is now sparse
var arr = [1,2,3];
arr[1] = undefined; // <- arr is not sparse
arr[10] = undefined; // <- arr is now sparse