Array.prototype.splice()
The one Array method that both mutates and returns something surprising. The demo below shows the return value: the elements taken OUT, not the array left behind.
Demo
Every output here is the list of elements REMOVED — that is what splice returns. Removing two from index 1 of [1,2,3,4,5] gives [2, 3] back, and leaves the original as [1, 4, 5], which the demo cannot show because the return value is all you get. A count of 0 removes nothing and returns an empty array, which is how you insert without deleting. A count past the end simply stops rather than erroring.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| start | number | yes | Index to begin changing at. Negative counts from the end. Beyond the length appends. |
| deleteCount | number | no (to the end) | How many elements to remove. Zero removes nothing, which is how you insert without deleting. Omitted entirely, everything from start onward is removed. |
| ...items | any | no (none) | Elements to insert at start, after the removal. Any number of them. |
Return value
Array — An array of the REMOVED elements — not the modified array. Empty when nothing was removed. The original array is modified in place.
Common patterns
items.splice(index, 1);
items.splice(2, 0, 'new');
items.splice(1, 2, 'a', 'b');
Examples
Pitfalls
const a = [1, 2, 3, 4]; const result = a.splice(1, 2); result
a.splice(1, 2); a
props.items.splice(0, 1);
const next = props.items.filter((_, i) => i !== 0);
for (let i = 0; i < a.length; i++) if (bad(a[i])) a.splice(i, 1);
a = a.filter(x => !bad(x));
[1, 2, 3, 4].splice(1)
[1, 2, 3, 4].splice(1, 1)
When to use
- Removing an element by index from an array you own
- Inserting at a position with deleteCount 0
- Replacing a run of elements in one call
- The array is shared or a prop → filter, or toSpliced
- You only want a copy of a range → slice
- You are removing inside a loop → filter
- You need the resulting array as the return value → toSpliced
Notes
FAQ
It returns what it REMOVED, which is by design — that is how you capture the elements you just cut out. The modified array is the original; splice has already changed it in place, so just read the variable you called it on.
const a = [1, 2, 3, 4]; const removed = a.splice(1, 2); removed; // [2, 3] a; // [1, 4]