0

I wrote a simple array where I have a few elements.

After deleting an element, I noticed that it outputted "empty" but I was expecting an undefined datatype.

  • I ran the same code on MDN and got an undefined as a result.

  • I ran the code in different browsers but got "empty" as a result.

When I looked for the type of this element it gave me an undefined as a result.

I was wondering why I got 2 different terms for something where the types are the same?

Thank you in advance!

Culhaci Lucas - JeWelCrax

    // code
    const pizzas = ["Margherita", "Mushroom", "Spinach & Rocket", undefined,"Pineapple & Sweetcorn"]
    delete pizzas[2];
    console.log(pizzas);
    console.log(typeof pizzas[2]);

    // output
    ['Margherita', 'Mushroom', empty, undefined, 'Pineapple & Sweetcorn']
    undefined
  • 1
    Follo [this](https://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice) link. Hope it will clear your doubt. – Shivam Mishra Feb 26 '22 at 18:43

1 Answers1

0

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320