A single method covers three moves that feel separate: removing an item in the middle of an array, inserting one without overwriting its neighbors, and replacing a portion with another.
The price is a real one: splice changes the original array, which makes it the most useful and the most dangerous array method at the same time.
Definition
splice(start, count, ...additions) works in place. The first argument is the position, the second the number of items to remove, the rest the items to insert there. The method hands back the array of removed items, not the changed array.
const tasks = ["write", "review", "publish"];
const removed = tasks.splice(1, 1);
console.log(removed); // [ 'review' ]
console.log(tasks); // [ 'write', 'publish' ]That return value is the source of a frequent misreading: const list = tasks.splice(1, 1) does not hold the list, only what was just torn out of it.
The three uses
const steps = ["write", "publish"];
// Insert without removing anything: second argument set to zero
steps.splice(1, 0, "proofread");
console.log(steps); // [ 'write', 'proofread', 'publish' ]
// Replace: remove one item and put another in its place
steps.splice(0, 1, "draft");
console.log(steps); // [ 'draft', 'proofread', 'publish' ]
// Remove everything from a position on: leave out the second argument
const tail = steps.splice(1);
console.log(steps); // [ 'draft' ]
console.log(tail); // [ 'proofread', 'publish' ]A negative start counts from the end, as with slice(): splice(-1, 1) removes the last item.
When not to reach for it
Changing an array in place becomes a problem as soon as that array is displayed somewhere else, an interface state in particular. The library sees no new value, so nothing is redrawn.
| The need | The method that changes | The copying equivalent |
|---|---|---|
| Remove an item | splice(i, 1) | Array.filter() |
| Add at the end | Array.push() | [...list, item] |
| Take a portion | splice(i, n) | slice() |
The table reads in three columns: the need, the method that touches the original, and the form that builds a new value. The right-hand column is the one to favor everywhere Immutability matters.
Frequently asked questions
How do you remove an item whose position is unknown?
By looking for it first, with indexOf() for a simple value or findIndex for an object, then checking the result is not -1 before calling splice. Without that check, splice(-1, 1) removes the last item of the array, which was not the request.
What does splice hand back when it removes nothing?
An empty array. A pure insertion therefore returns [], which is consistent but rarely useful. To know the new size of the array after the operation, read length on the array itself.
Is there a version that changes nothing?
Yes, toSpliced takes the same arguments and hands back a new array while leaving the original intact. The method is recent, so check support in your target browsers, or rebuild the array with Spread (...) and slice().