![]() |
VOOZH | about |
The splice() method in JavaScript is used to change the contents of an array by removing, replacing, or adding elements. It directly modifies the original array, making it useful for dynamic data manipulation.
Syntax
array.splice(startIndex, deleteCount, item1, item2, ..., itemN);Return Value: While it mutates the original array in place, still it returns the list of removed items. In case there is no removed array it returns an empty array.
The splice() method can perform different tasks depending on the parameters provided.
The splice() method can be used to remove elements from an array. This is done by providing the startIndex and the deleteCount (the number of elements to remove).
we can also use splice() to add elements to an array without removing any. To do this, set deleteCount to 0 and provide the elements to add.
We can also use splice() to replace elements. Provide the startIndex, deleteCount, and the elements to replace the removed items.
Since splice() works with any position in the array, you can use it to add or remove elements from the end of the array by using a startIndex equal to the array length.
We can also use negative numbers for the startIndex to remove or add elements starting from the end of the array. Negative indices count from the end, where -1 refers to the last element, -2 to the second last, and so on.