This is just an oddity of the console when displaying sparse arrays.
When a normal (non-sparse) array is logged in the console, all elements will be displayed, with a comma between them.
When one of those elements contains the value undefined
, undefined
will be displayed.
When the array is spare, the array doesn't have a value at a particular index - rather, it's that the array doesn't have that index at all. This is an odd situation, and to distinguish this from the array containing the value undefined
, the console will display empty
.
That is, it was decided that it was useful to be able to distinguish
const arr = [1, undefined, 3]
// arr now has own properties 1 and 2 and 3
from
const arr = [1, 2, 3]
delete arr[1];
// arr now has own properties 1 and 3
In your code, the array actually contains the same values on MDN and in browsers - it's just that they have different ways of displaying nonexistent indicies.
The best way to approach this sort of thing is to never have sparse arrays - they're confusing and don't have much of a purpose in well-designed code. If you want to have a collection of keys and values, where the keys are integers but not necessarily all of them will exist in ascending order, use an object instead of an array.
// This code is perfectly fine:
const pizzas = {
0: "Margherita",
1: "Mushroom",
2: "Spinach & Rocket"
// ...
}
delete pizzas[1];
If you want an array and you want to remove an element such that the indicies shift down when an element is removed, I'd use .filter
.
const pizzas = ["Margherita", "Mushroom", "Spinach & Rocket", undefined,"Pineapple & Sweetcorn"];
const pizzasWithoutSpinach = pizzas.filter((_, i) => i !== 2);
console.log(pizzasWithoutSpinach);