Delete elements
Remove a contiguous section when its index and length are known.
JavaScript · Function
splice() changes an array in place by removing, replacing, and/or inserting elements. It returns a new array containing the elements removed.
Call splice() on an array with a starting index, an optional removal count, and optional replacement elements. It changes the array itself, removes the requested elements, inserts the supplied items at that position, and returns a new array containing what was removed.
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)| Name | Type | Description |
|---|---|---|
start | integer | Zero-based position at which changes begin; negative values count from the end. |
deleteCount | integer | Number of elements to remove starting at start. |
item1, …, itemN | any | One or more values inserted at start after removals. |
A new array containing the elements removed from the original array.
const months = ["Jan", "March", "April", "June"];
const removed = months.splice(1, 1, "Feb");
console.log(months); // ["Jan", "Feb", "April", "June"]
console.log(removed); // ["March"]Replaces one element at index 1, mutates the original array, and returns the removed elements.
Remove a contiguous section when its index and length are known.
Insert values at a chosen position without deleting existing entries.
Swap existing values while preserving the array's position structure.
splice() mutates the receiver and returns an array containing the elements removed. Its arguments determine where changes begin, how many elements are removed, and which new elements are inserted.
Follow-up: How would you perform the same operation immutably? Use toSpliced(), which is the copying version of splice().
start is the zero-based position where modification begins. A negative start counts backward from the end, while a value beyond the array is handled as the effective end position.
Follow-up: What happens when start is negative but outside the array range? The documented conversion rules clamp it to the beginning of the array.
deleteCount specifies the number of existing elements removed from start. item1 through itemN are inserted at that same position, and the returned array contains the removed elements.
Follow-up: How can splice() insert without removing? Pass a deleteCount of 0 and provide the elements to insert.
Array.prototype.toSpliced()Array.prototype.push()Array.prototype.unshift()