JavaScript Reference ยท Array
Array.prototype.splice()
Reference for JavaScript Array.prototype.splice(): remove, insert or replace elements in place, the returned array of removed items, negative indexes and toSpliced().
The splice() method changes an array by removing, replacing or inserting elements at any position. It works in place and returns a new array containing the elements it removed (an empty array if it removed none).
It is the general-purpose editing tool for arrays. Because it mutates, prefer toSpliced() when you need an updated copy and want to leave the original alone.
const list = ["a", "b", "c", "d"]; list.splice(1, 2); // returns ["b", "c"] // list is now ["a", "d"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.splice(start) array.splice(start, deleteCount) array.splice(start, deleteCount, item1) array.splice(start, deleteCount, item1, item2, /* ..., */ itemN)
| Name | Description |
|---|---|
start |
Index where changes begin. Negative values count from the end. Values beyond the length are clamped to the length. |
deleteCount |
Optional. How many elements to remove from start. If omitted, everything from start to the end is removed. 0 (or less) removes nothing. |
item1, ..., itemN |
Optional. Elements to insert at start, after any removal. |
Return value: an array of the removed elements, in their original order.
Exceptions: a TypeError if the array is frozen, or if the change would make the length exceed the maximum.
Usage notes
- It mutates and returns the removed items, not the array.
list = list.splice(0, 1)throws away the list. Use the return value only when you want what was taken out. - Omitting
deleteCountremoves everything fromstartto the end, but passingundefinedexplicitly removes nothing (it is converted to0). Callingsplice()with no arguments does nothing and returns[], whilesplice(undefined)hasstartof0and removes every element. - When
startis beyond the length, nothing is removed, and any new items are appended at the end. - Remove by value by finding the index first with
indexOf()and checking it is not-1. A-1would remove the last element. - Removing while looping forward skips elements because indexes shift. Loop backward, or build a new array with
filter(). - Slice versus splice:
slice()copies without changing the array;splice()changes it. - Immutable style:
toSpliced()takes the same arguments and returns a changed copy.filter()removes,with()replaces one item and[...a.slice(0, i), x, ...a.slice(i)]inserts, all without mutation. - Cost. Inserting or removing near the start moves many elements; it is O(n).
- Sparse arrays: holes in the removed range are preserved as holes in the returned array.
Browser support
Array.prototype.splice() is part of ES3 and works everywhere. toSpliced() is newer, so check a compatibility table before relying on it.