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

← All JS array methods · TypeScript vs JavaScript