splice method in javascript
The
splice() method in JavaScript is a powerful array method used to change the contents of an array by removing, replacing, or adding elements at a specified position. It directly modifies the original array and returns an array containing the removed elements (if any).
Syntax:
array.splice(startIndex, deleteCount, item1, item2, ..., itemN);
Parameters:
-
The index at which to start changing the array.
- If
startIndexis negative, it's treated as an offset from the end of the array (e.g., -1 refers to the last element).
- If
- If
startIndexis greater than the array's length, it's treated as the array's length. -
The number of elements to remove from the array, starting from
startIndex.
If
deleteCount is 0, no elements are removed.If
deleteCount is omitted or greater than the number of elements remaining after startIndex, all elements from startIndex to the end of the array are removed.The elements to add to the array, starting from
startIndex, after any elements have been removed.Return Value:
The
splice() method returns an array containing the removed elements. If no elements are removed, it returns an empty array.
Common Use Cases:
removing elements.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 2); // Removes 2 elements starting from index 1 ('March', 'April')
// months is now ['Jan', 'June']
adding elements.
const fruits = ['apple', 'banana', 'cherry'];
fruits.splice(2, 0, 'grape', 'lemon'); // At index 2, remove 0 elements, then add 'grape' and 'lemon'
// fruits is now ['apple', 'banana', 'grape', 'lemon', 'cherry']
replacing elements.
const colors = ['red', 'green', 'blue'];
colors.splice(1, 1, 'yellow'); // At index 1, remove 1 element ('green'), then add 'yellow'
// colors is now ['red', 'yellow', 'blue']
Important Note: The
splice() method modifies the original array directly. If you need to manipulate a portion of an array without changing the original, consider using the slice() method instead, which returns a new array with the selected elements