The splice()
method in JavaScript is used to change the contents of an array by removing or replacing existing elements and/or adding new elements in place.
Syntax
array.splice(start, deleteCount, item1, item2, ...);
Parameters
Parameters | Descriptions |
---|---|
start | The index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, it will begin that many elements from the end of the array (with origin -1, meaning -n is the index of the nth last element and is therefore equivalent to the index of array.length – n) and will be set to 0 if negative. |
deleteCount | An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. |
item1, item2, … | The elements to add to the array, beginning from start. If you don’t specify any elements, splice() will only remove elements from the array. |
Return Value
Return Type | Description |
---|---|
Array | An array containing the deleted elements. If no elements are deleted, an empty array is returned. |
Example 1: Removing Elements
This example demonstrates how to use the splice()
method to remove elements from an array.
let Arr = [ 10, 20, 30, 40, 50 ]; let removedItems = Arr.splice(1, 2); console.log('Removed Items:', removedItems); console.log('Updated Array:', Arr);
Output:
Removed Items: [ 20, 30 ]
Updated Array: [ 10, 40, 50 ]
Example 2: Adding Elements
You can also use the splice()
method to add elements to an array.
let Arr = [ 10, 20, 30, 40, 50 ]; Arr.splice(2, 0, 25, 28, 29); console.log('Updated Array:', Arr);
Output:
Updated Array: [
10, 20, 25, 28,
29, 30, 40, 50
]
Example 3: Replacing Elements
The splice()
method can also be used to replace elements in an array.
let Arr = [ 10, 20, 30, 40, 50 ]; Arr.splice(1, 1, 12, 15); console.log('Updated Array:', Arr);
Output:
Updated Array: [ 10, 12, 15, 30, 40, 50 ]
Note
The splice()
method modifies the original array and returns an array containing the removed elements or an empty array if no elements were removed.
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |