2

I am confused about delete operator use on array element.

I found that delete can be used with array elements and it removes the element but doesn't update array length , so basically that element is replaced with undefined.But when i tested it I found that it replaces it with blank.

var test = new Array()
delete test[id];

So i have 3 points regarding this

  1. test[id] id in this is element or index of element, as I read that id can be both. But when I tested it , I found its working only when i pass index.

  2. What if the array has no element and I try to delete by passing any value like delete test[3]?

  3. when i delete an element then it replaces that with undefined or blank?
Anita
  • 2,352
  • 2
  • 19
  • 30

1 Answers1

4

Don't use delete on array, use splice()

  1. delete will not remove the element actually from array. It'll just set the value to undefined
  2. delete does not alter the length of array

delete Demo

var arr = [1, 2, 3, 4, 5];

delete arr[2];

document.write(arr);
console.log(arr);
document.write('<br />Length: ' + arr.length);

Use splice()

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

splice() will return silently, if you passed an out of bound index to remove.

arr.splice(indexToDelete, 1);

splice() Demo

var arr = [1, 2, 3, 4, 5];

arr.splice(2, 1);
arr.splice(100, 1); // For out of bounds index, it fails silently

document.write(arr);
console.log(arr);
document.write('<br />Length: ' + arr.length);
Tushar
  • 85,780
  • 21
  • 159
  • 179