Let’s look a few key differences that are most likely to cause issues when working with these methods:
|Modifies the original array.||Does not modify the original array.|
|The second parameter is not an index, but a number of records to remove||The second parameter is a non-inclusive end index.|
|Can be used to add or remove items from an array.||Used to remove items from an array. Or more accurately, creates an array that’s a subset of the original array.|
Adding with array.splice()
First, let’s define an array of colors to work with in our examples:
let colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple", "White", "Black", "Gray", "Brown"];
colors.splice(2, 0, 'Orange Yellow');
Our array now contains “Orange Yellow”:
By taking advantage of the second parameter, we can use splice() to replace values in our array.
Let’s use splice() to replace “Purple” with “Violet”:
colors.splice(6, 1, 'Violet');
Now our array looks like this:
Removing with array.splice()
Since this is the functionality most likely to be confused with slice(), let’s now look at removing values with splice().
Let’s remove the “Orange Yellow” value that we added to our array:
We can see that “Orange Yellow” is now gone from our array:
Removing with array.slice()
Let’s assume that our array is reset to the original array we defined and use the slice() method to create a subset of that array.
Imagine that we now want an array of just the warm colors in our colors array. We can slice the first three colors into a new array:
let warmColors = colors.slice(0, 3);
Our warmColors array will contain the first three colors:
In this post, we had a quick overview of the differences between array.splice() and array.slice() and then looked at a few examples of their usage.
The example code is available on a CodePen for further experimentation and is also available over on BitBucket for those that prefer to download and work with the source locally.