lYriCAlsSH lYriCAlsSH - 6 months ago 30
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
Array.splice
method
? 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

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

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> 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"]