The Array.splice()
method is a built-in JavaScript function used to add, remove, or replace elements in an array. It modifies the original array directly and is commonly used for tasks requiring precise control over array elements.
Syntax
arr.splice(start, deleteCount, item1, item2, ..., itemN);
Parameters
Parameter | Description |
---|---|
start | (Required) The index at which to start changing the array. Negative values count from the end of the array. |
deleteCount | (Optional) The number of elements to remove from the array. If omitted, all elements from start to the end are removed. |
item1, …, itemN | (Optional) The elements to add to the array, starting at the start index. If no elements are provided, splice() only remove elements. |
Return Value
The splice()
method returns an array containing the removed elements. If no elements are removed, it returns an empty array.
Example 1: Removing Elements
let arr = [10, 20, 30, 40, 50]; let removed = arr.splice(1, 2); console.log(removed); // Output: [ 20, 30 ] console.log(arr); // Output: [ 10, 40, 50 ]
Example 2: Adding Elements
let arr = [10, 40, 50]; arr.splice(1, 0, 20, 30); console.log(arr); // Output: [10, 20, 30, 40, 50]
Example 3: Replacing Elements
let arr = [10, 20, 30, 40, 50]; arr.splice(1, 2, 100, 200); console.log(arr); // Output: [ 10, 100, 200, 40, 50 ]
Example 4: Removing All Elements from a Starting Index
let arr = [10, 20, 30, 40, 50]; let removed = arr.splice(2); console.log(removed); // Output: [ 30, 40, 50 ] console.log(arr); // Output: [ 10, 20 ]
Example 5: Using Negative Indices
let arr = [10, 20, 30, 40, 50]; arr.splice(-2, 1); console.log(arr); // Output: [ 10, 20, 30, 50 ]
Example 6: Clearing an Array
let arr = [10, 20, 30, 40, 50]; arr.splice(0, arr.length); console.log(arr); // Output: []
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |