0

I'm reading the delete unary operator talked about near bottom of page here (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Unary)

It says deleting an item from an array will make the item undefined. However, as the code below shows, we cannot loop over this undefined item like we can do with a fresh array with the explicit value of undefined as one of its items.

Is this just a quirk or is there more to read into here? It doesn't seem meaningful to describe the deleted item as undefined when it's not treated like undefined.

let a = [1, 2, 3];

console.log("untampered-with array:", a);

delete a[0];

console.log("array after first item deleted:", a);

a.forEach(element => {
    console.log("looping over each item and printing it:", element);
});

b = [undefined, 1, 2];

b.forEach(element => {
    console.log("looping over each item of array with undefined explicitly declared:", element);
});

It might also be worth mentioning that in Visual Studio Code, when we print out a after the first item is deleted, it does not show the first item as undefined (like it does on the Stack Overflow code simulator). It shows this: enter image description here

tonitone110
  • 139
  • 6
  • 2
    is there a question in here? – Joe Jun 21 '20 at 15:11
  • 1
    It creates a *hole* in the array. `forEach` and other arrray methods skip over the holes: https://stackoverflow.com/a/13847793/3082296 – adiga Jun 21 '20 at 15:13
  • "*`trees[3]` is removed with delete. However, `trees[3]` is still addressable and returns undefined*" - that's not expressed very well. *Any* property is addressable in javascript regardless whether it exists or not, and returns `undefined` when it doesn't exist, there's nothing special about arrays here. – Bergi Jun 21 '20 at 15:24
  • 1
    [Do not use `delete` on arrays](https://stackoverflow.com/q/500606/1048572). Never. I'll update MDN to include a warning. – Bergi Jun 21 '20 at 15:24

2 Answers2

0

You can use splice method to remove array items instead of using delete.

0

You can either use splice

let b = a.splice(0, 1)

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/splice

or filter

let b = a.filter((item, i) => { return i !== 0 })

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter

In both case, b is a new array without the item indexed at 0.