lYriCAlsSH lYriCAlsSH - 11 months ago 72
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?


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"]