Why does a javascript array continue to the same size even when we use delete?

Asked

Viewed 54 times

2

I was running some tests on javascript and I realized that when I use the function delete in an index of a array, the array is still the same size.

Example:

a = [1, 2, 3]

delete a[1]

console.log(a.length); // Imprime 3

Why does this happen?

  • The delete only removes the assigned value. It is a question of data structure. A array is a limited and fixed sequence of memory lained positions. If you want to manipulate a list you must use a chained list, not natively present in Javascript.

1 answer

7


The delete only arrow the index value passed from the array to undefined.

delete a[1];
console.log(a); //[1,undefined,3]

To remove an index from the array you can use the Array.splice

a.splice(1,1); //vai retornar o indice removido [2]
console.log(a); //[1,3]
  • 1

    How interesting, even if the deleted element is the last the size remains 3! While in the assignment the length is updated (eg.: a[10] = 4 does the length become 11). This is another Javascript weirdo I didn’t know...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.