Nikhil Pai
Nikhil Pai

Reputation: 125

How does delete exactly work?

Please check the jsfiddle - http://jsfiddle.net/du8svaym/

var a = [2, 4, "bang", undefined, NaN, 5];

for (i in a)
alert(a[i]); //alerting a[3]=undefined

delete a[1];
for (i in a)
alert(a[i]); //Why not alerting a[1]= undefined?

alert(a[1]); //it is undefined! but not alerted, what is happening under the hood?

If you notice, the first loop alert alerts a value which is undefined. In the 2nd loop alert a[1] is undefined since we deleted it, but is not alerted. What is the difference between the two undefined, how exactly or differently is delete setting the undefined?

Upvotes: 0

Views: 96

Answers (3)

dr_dev
dr_dev

Reputation: 522

For the first iteration, the array looks like this.

[0: 2, 1: 4, 2: "bang", 3: undefined, 4: NaN, 5: 5]

Now, after you delete a1, it removes 4. So, now the array looks like

[0: 2, 2: "bang", 3: undefined, 4: NaN, 5: 5]

Now, as you can see a1 does not exist. So it gives undefined.

Deleting an element will not affect the array length, as it does not change the indexes. If you want the array index to be affected, use splice.

Upvotes: 1

David Hughes
David Hughes

Reputation: 378

The delete operator removes a property from an object. Arrays are JavaScript objects like so:

var foo = {
  '0': 2,
  '1': 4,
  '2': "bang",
  '3': undefined, 
  '4': NaN,
  '5': 5
}
delete foo[1]; // completely removes the property '1' from foo.
console.log(foo);
// outputs:
{
  '0': 2,
  '2': "bang",
  '3': undefined, 
  '4': NaN,
  '5': 5
}

Upvotes: 2

unobf
unobf

Reputation: 7244

JavaScript Arrays are sparse, that means that they do not have to store a value at every position. Delete removes the value at the position, making it sparse.

Try this

a = []; // empty array
a[1000] = 'hello';
for (i in a) {
    console.log(i);
}
console.log(a.length)

You will see that it will only print 1000 in the loop whereas the length of the array is 1001

Upvotes: 0

Related Questions