lYriCAlsSH lYriCAlsSH - 2 years ago 211
Javascript Question

Deleting array elements in Javascript - delete vs splice

What is the difference between using the

operator on the array element as opposed to using the
? For example:

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];
// or
myArray.splice (1, 1);

Why even have the splice method if I can delete array elements like I can with objects?

Answer Source

Delete in this case will only set the element as undefined:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
> myArray
  [undefined, "b", "c", "d"]

Splice actually removes the element from the array:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download