JavaScript Array splice()

The splice() method modifies an array (adds, removes or replaces elements).

Example


splice() Syntax

The syntax of the splice() method is:

arr.splice(start, deleteCount, item1, ..., itemN)

Here, arr is an array.


splice() Parameters

The splice() method takes in:

  • start - The index from where the array is changed.
  • deleteCount (optional) - The number of items to remove from start.
  • item1, ..., itemN (optional) - The elements to add to the start index. If not specified, splice() will only remove elements from the array.

splice() Return Value

  • Returns an array containing the deleted elements.

Note: The splice() method changes the original array.


Example 1: Using splice() method

Output

[ 'Java', 'Lua' ]
[ 'JavaScript', 'Python', 'C', 'C++' ]
[]
[ 'JavaScript', 'Java', 'Lua', 'Python', 'C', 'C++' ]
[ 'Lua', 'Python', 'C' ]
[ 'JavaScript', 'Java', 'C++' ]

Example 2: Using splice() for different deleteCount values

  • If start > array.length, splice() does not delete anything and starts appending arguments to the end of the array.
  • If start < 0, the index is counted from backward (array.length + start). For example, -1 is the last element.
  • If array.length + start < 0, it will begin from index 0.

Output

[]
["JavaScript", "Python", "Java", "Lua", "C++"]
[ 'C++' ]
["JavaScript", "Python", "Java", "Lua", "Swift", "Scala", "Go"]

Example 3: Using splice() for different start values

  • If deleteCount is omitted or is greater than the number of elements left in the array, it deletes all elements from start to end of the array.
  • If deleteCount is 0 or negative, no elements are removed. But, at least one new element should be specified.

Output

[ "Python", "Java", "Lua" ]
[ "JavaScript" ]
[ ]
["JavaScript", "Swift", "Scala", "Go"]

Recommended Readings: