mutation
Array.prototype.splice
Removes and/or inserts elements at any position in the array, returning the removed items. Reach for it to do insert/delete/replace edits in one call.
arr.splice(start, deleteCount, ...items) Parameters
| Parameter | Purpose |
|---|---|
| start | Index to begin the change; negative counts from the end |
| deleteCount | Number of elements to remove starting at `start` |
| ...items | Optional values to insert at `start` |
Examples
const a = [1,2,3,4]; const removed = a.splice(1, 2); console.log(a, removed); Logs: [1, 4] [2, 3]
const a = [1, 4]; a.splice(1, 0, 2, 3); console.log(a); Logs: [1, 2, 3, 4] (insert without deletion)
const a = [1, 2, 99, 4]; a.splice(2, 1, 3); console.log(a); Logs: [1, 2, 3, 4] (replace one item)
const a = [1,2,3]; const b = a.toSpliced(1, 1); console.log(a, b); Logs: [1, 2, 3] [1, 3] (ES2023 non-mutating alternative)
Gotcha
MUTATES the source AND returns the removed items — not the resulting array. Use `toSpliced()` (ES2023) for a non-mutating copy.
Related methods
Array.prototype.slice
Returns a shallow copy of a portion of the array from start (inclusive) to end (exclusive) without modifying the source. Reach for it to extract a range or to clone an array (`arr.slice()`).
Array.prototype.push
Appends one or more elements to the end of the array and returns the new length. Reach for it to grow a list — it's the canonical "add to the end" call.
Array.prototype.pop
Removes the last element from the array and returns it (or undefined if empty). Reach for it to consume the tail of a list — the natural pair to push for stack behavior.
Array.prototype.shift
Removes the first element from the array and returns it, reindexing every remaining element. Reach for it to consume the head of a list — the natural queue operation.
Array.prototype.unshift
Prepends one or more elements to the front of the array and returns the new length. Reach for it to insert at the head — but be aware every existing item is reindexed.