According to MDN:
When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.
Then to be wrong is your last assumption ("array only has two elements now"). As noted by RobG in comments this is wrong for two reasons:
Array.length
is the length of an array (see last §15.4.5.2 cited later), not number of elements it contains.
- In your case
a.length
is not two but three because delete
doesn't trim arrays.
What does it means? That comment is right (a
has two elements) but code is wrong (array length is still three).
When you delete an element from an array what you get is undefined
instead of that element (when you try to access that index):
var a = [1,2,3]; // a == [1, 2, 3]
delete a[2]; // a == [1, 2, undefined]
From ECMAScript Language Specification.
delete
operator is described in §11.4.1. It says [[Delete]]
array internal method it'll be called. Now we know (from §8.6.2) we should check [[DefineOwnProperty]]
array internal method because simply deleting an index property is not enough. From §15.4.5.1 we can see that length
property can be changed to truncate array but it won't be affected deleting (removing) an array item because it won't do any assignment (then §15.4.5.1 won't apply). You'll get undefined
because now there isn't such member and according to §8.6.1 result is then undefined
.
In my opinion (but it's just speculation) confusion arises from §15.4.5.2 where they say:
The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.
According to this single sentence then removing last element of an array may also reduce its length. This behavior doesn't fulfill §15.4.5.1 and standard just states that length
is greater than...array index, not exactly highest index + 1.
To summarize in simple words: delete
operator simply deletes a member but length
is unaffected.