Why does the array still have a non-zero length after deletion?

arrays, javascript

Solution

`delete` is a "lower level" operator. It directly works on the object, it doesn't "know" about the array. Using `delete` simply doesn't trigger the routine to recompute the array length.

Other answers here claim that the value of the property is set to `undfined`, which is incorrect. A simple test shows that:

var a = [1]; 
delete a[0]; 
console.dir(a);

and compare to what happens if you really set the value to `undefined`:

var a = [1]; 
a[0] = undefined; 
console.dir(a);

For a more solid proof, lets have a look at the specification:

When the [[Delete]] internal method of O is called with property name P and the Boolean flag Throw, the following steps are taken:

- Let desc be the result of calling the [[GetOwnProperty]] internal method of O with property name P.

- If desc is undefined, then return true.

- If desc.[[Configurable]] is true, then a. Remove the own property with name P from O. b. Return true.

- Else if Throw, then throw a TypeError exception.

- Return false.

Nowhere it is said that the value of the property is set to `undefined`.

The consoles of different browsers might show different representations of the array. In this particular example, you can argue whether it should be `[]` or `[undefined]`.

`[]` (Chrome) seems to make sense because the array really doesn't have any elements, there are no properties with numeric names. However, when you access the `.length` property, you would get a `1`, which can be confusing. Not too long ago, Chrome used a representation like `[undefined x 5]` to indicate an array of length 5 but without elements. I think this was actually a good solution.

`[undefined]` (Firefox) makes sense because the array is of length 1 and accessing `arr[0]` actually returns `undefined` (but so does `arr[10]`).However, `arr.hasOwnProperty(0)` would be `false` and if an array really contains the value `undefined`, how can it be distinguished from an empty array of length one solely by this representation (answer: you can't).

The bottom line is: Don't trust `console.log` too much. Rather use `console.dir` if you want an exact representation.

Problem

I have the following code that outputs the length of an array, deletes it, and then outputs the new length: ``` console.log($scope.adviceList.activeAdvices.length); // *1* $scope.adviceList.activeAdvices.splice(id,1); // *id is a parameter* console.log($scope.adviceList.activeAdvices.length); // *0* console.log($scope.adviceList.activeAdvices.length); // *1* delete $scope.adviceList.activeAdvices[id]; console.log($scope.adviceList.activeAdvices.length); // *0* console.log($scope.adviceList.activeAdvices); // *[]* ``` After the deletion, the array is correctly displayed as empty. Its length, however, is still 1.

Original source

Related problems