3

As an example, when using the delete operator on an index of an Array, the index is removed, such as any property of any object would be.

This is proven by:

var arr = ['one', 'two', 'three'];

delete arr[1];

if(1 in arr)
    alert("It didn't work!");

If you were to run this block, you will find that the text "It didn't work!" will never be alerted to the user. This is because the property belonging as index 1 on the Array has been deleted.

Now, here is where things get weird...

Although an index is deleted from an Array, the Array length shall remain the same:

var arr = ['one', 'two', 'three'];

alert(arr.length); //will alert '3'

delete arr[2];

alert(arr.length); //will still alert '3'

When looking at the Array arr in the debugger (in Chrome at least), you will see that the index 2 does not even exist, so why does the length still report as 3?

Here is a JSFiddle to play around with.

WebWanderer
  • 10,380
  • 3
  • 32
  • 51
  • I did not see these posts before-hand, as they did not appear during my searches. I agree that my question may be a duplicate. My apologies. – WebWanderer Mar 10 '15 at 18:21

1 Answers1

3

the array actually loses the key when you call delete one of it's keys, so if you do

Object.keys(arr)

you would see that the key is missing and replaced by undefined.

edit: the other posts mentioned have better answers, but here is my take. delete doesn't adjust the size , when you all push, put gets called using the last size it knows. some browsers just show undefined instead of the deleted value key.

Abraham Adam
  • 635
  • 1
  • 6
  • 16