JavaScriptArrays

Array.prototype.splice()

Removes, replaces, or inserts elements in place, changing the array.

Returns
An array of the removed elements (it can be empty).
Changes the original
Yes
On this page

Example

#
JavaScript
const list = ['HTML', 'CSS', 'PHP', 'JavaScript']

const removed = list.splice(2, 1)
console.log(removed)
console.log(list)

list.splice(1, 0, 'Sass')
console.log(list)
Console
['PHP']
['HTML', 'CSS', 'JavaScript']
['HTML', 'Sass', 'CSS', 'JavaScript']

Definition and usage

#

The splice(start, deleteCount, ...items) method changes the original array. Starting at index start, it removes deleteCount elements and inserts the given new elements in their place. It returns an array of the removed elements.

With a single call you can remove an element (splice(i, 1)), insert a new one without removing anything (splice(i, 0, x)), or swap a chunk for other values.

If you don’t want to mutate the data, use the newer toSpliced() method, which works the same way but returns a new array.

Syntax

#
Syntax
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, …)

Parameters

#
  • start

    number

    The index the changes start at. A negative value counts from the end.
  • deleteCount

    optional

    The number of elements to remove. Omitted means removing everything to the end.
  • item1…itemN

    optional

    The elements to insert at start.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • To remove an element by condition, filter() is usually the better choice, since it doesn’t mutate the array.
  • Don’t remove elements with splice() in a loop going forward, since the indexes shift. Go backward instead, or use filter().

Related entries

#

Spotted a mistake or missing an example? Write to us.