Array.splice() vs Array.slice()

The splice() method

  • returns the removed item(s) in an array
  • changes the original array
  • can take n number of arguments:

Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.

Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.

Argument 3…n: Optional. The new item(s) to be added to the array.

Syntax

array.splice(index, howmany, item1, ….., itemX)

The slice() method

  • returns the selected element(s) in an array, as a new array object
  • doesn’t change the original array
  • can take 2 arguments:

Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.

Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

Syntax

array.slice(start, end)

Example with slice using a negative number to select from the end of an array (in this case we don’t start the counting from 0 as we do with positive numbers)

Leave a comment