The splice function is used to add elements to or remove elements from an array at a given index, and it returns the elements removed from the array. The syntax for the splice function is as follows:
Here, index is the position at which we want to add or remove elements, removeCount, which is an optional argument, is the number of elements that we want to remove, and items, which is also optional, contains the elements we want to add.
Now, we will go over a few examples to show how the splice function is implemented.
First, suppose we have an array that consists of five elements.
To remove the elements 20 and 30 (at position 1 and position 2 in the array, respectively) from the array, we simply call the splice function and tell it to start from the first index and remove 2 elements.
The values 20 and 30 are returned as the output. Next, we can look at the original array with the following command:
The two elements returned in the output are no longer in the array.
Next, we will add elements to the array using the splice function. Because we will not remove elements from the array, we can provide a value of zero for removeCount and then provide the elements we want to add.
The above command returns an empty array because no elements were removed. However, if we look at the original array, we can see that it has been updated.
The values 30 and 35 were successfully added at the second index.
Finally, if we want to remove elements and add elements, we can provide values for both removeCount and items.
The above command has returned the two elements that were removed, and if we print the original array to the console, we can see that 20 and 30 are no longer in the array and that 15, 20 and 25 have been added.