Array .splice()
A method that adds, removes, or replaces elements at any position in an array. It modifies the original array directly.
Syntax
// Removes elements starting at the specified index. var removed = array.splice(startIndex, deleteCount); // Inserts elements at the specified index without removing any. array.splice(startIndex, 0, item1, item2, ...); // Replaces elements at the specified index. array.splice(startIndex, deleteCount, item1, item2, ...);
Arguments
| Argument | Description |
|---|---|
| startIndex | The index at which to start the operation. A negative value counts from the end of the array. |
| deleteCount | The number of elements to remove. Specify 0 to insert without removing. If omitted, all elements from startIndex to the end are removed. |
| items | Optional. Elements to insert at the start position. Multiple elements can be specified as comma-separated values. |
Sample Code
var colors = ["red", "blue", "green", "yellow", "white"]; // Removes 2 elements starting at index 1. var removed = colors.splice(1, 2); console.log(removed); // Outputs "blue,green". console.log(colors); // Outputs "red,yellow,white". // Inserts elements at index 1 without removing any. colors.splice(1, 0, "purple", "orange"); console.log(colors); // Outputs "red,purple,orange,yellow,white". // Replaces the element at index 2. colors.splice(2, 1, "pink"); console.log(colors); // Outputs "red,purple,pink,yellow,white".
Description
array.splice() is a versatile method that can remove, insert, and replace elements at any position in an array in a single call. It is a mutating method that modifies the original array in place, and its return value is an array of the removed elements. If no elements were removed, an empty array is returned.
If you specify a negative value for the start index, it is treated as an offset from the end of the array. For example, -1 refers to the last element, and -2 refers to the second-to-last element. If you omit the second argument, all elements from the start index to the end are removed, which is convenient when you want to truncate the end of an array.
If you want to extract a portion of an array without modifying the original, use array.slice() instead. The names look similar, but there is an important difference: array.splice() modifies the original array, while array.slice() does not.
Browser Compatibility
4.5 or earlier ×
3 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.