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?
4
  • The delete operator removes a property from an object. -- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 28, 2015 at 7:15
  • Why don't you just try it? Commented Aug 28, 2015 at 7:36
  • @torazaburo Yes I tried it finally and I am updating the question Commented Aug 28, 2015 at 7:37
  • [] is better than using new Array() to create new Array Commented Aug 28, 2015 at 10:43

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.