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.

1
  • 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. Commented Mar 10, 2015 at 18:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Woah! That's actually really cool! Thanks @Abraham Adam!
You can use the splice function with the second parameter as 1, example: [1,2,3,4,5].splice(5, 1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.