Skip to main content

What does splice() do?

It can remove, add and replace elements right in the original array.

Syntax

javascript
array.splice(start, deleteCount, item1, item2, ...);
ParameterWhat it does
startThe index at which changes start
deleteCountHow many elements to remove
item1, item2, ...Elements to insert in place of the removed ones (optional)

1. Removing elements

javascript
const arr = ["a", "b", "c", "d"]; const removed = arr.splice(1, 2); console.log(arr); // ["a", "d"] console.log(removed); // ["b", "c"]
  • From position 1, remove 2 elements.
  • Returns an array of the removed elements.
  • The original array is changed.

2. Adding elements

javascript
const arr = ["a", "d"]; arr.splice(1, 0, "b", "c"); console.log(arr); // ["a", "b", "c", "d"]
  • deleteCount = 0 means nothing is removed.
  • We add "b" and "c" at position 1.
  • Everything that came after shifts to the right.

3. Replacing elements

javascript
const arr = ["a", "b", "c"]; arr.splice(1, 1, "x", "y"); console.log(arr); // ["a", "x", "y", "c"]
  • Starting at index 1, remove 1 element ("b")
  • and insert "x", "y" in its place.
  • You can think of this as removal + insertion at the same time.

4. Using negative indexes

javascript
const arr = [1, 2, 3, 4]; arr.splice(-2, 1); // remove one element starting from the end console.log(arr); // [1, 2, 4]

-2 means "the second element from the end".

5. If you remove more than exists

javascript
const arr = [1, 2]; arr.splice(1, 10); console.log(arr); // [1]

The method does not throw an error, it just removes everything there is starting from position 1.

In short:

What it doesExampleResult
Removesarr.splice(1, 2)Removes 2 elements starting at index 1
Addsarr.splice(2, 0, "x")Inserts "x" at position 2
Replacesarr.splice(1, 1, "x")Changes 1 element to "x"
Returns["removed elements"]array of removed values
Mutates the original arrayYes

An "all at once" example

javascript
const arr = [1, 2, 3, 4, 5]; // remove 2 elements starting at index 1 and insert new ones const removed = arr.splice(1, 2, "a", "b", "c"); console.log(arr); // [1, "a", "b", "c", 4, 5] console.log(removed); // [2, 3]

Summary: splice() is a universal "Swiss army knife" for arrays: it removes, adds and replaces elements right in the original array and returns an array of the removed values.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.