JavaScript Array Methods: Splice() vs Slice()
The JavaScript methods splice()
and slice()
are similar methods that can be used to modify arrays. The main difference between the two is that the slice()
method returns a copy of the original array, as such, it does not modify the original array.
Let's take a look at the methods individually beginning with the splice()
method
Splice()
The splice()
method takes one compulsory parameter, the index at which to start modifying the array.
We should take notice of the fact that the original array has been modified.
The splice()
method can also take a second parameter and multiple other parameters. The second parameter will be the number of items to be removed or deleted. The remaining parameters are elements to be added to the array.
..and a second example with parameters to be added to the array
The splice()
method can also take a negative value for the start index, this means the index count will begin from the right of the array, bearing a value of -1.
Having taken a look at the splice()
method, let's now evaluate the slice()
method.
Slice()
The slice()
method takes one compulsory parameter, the index to begin and an optional index to end. The method returns a copy of the original array without modifying it.
We should take note that in the second snippet, the second parameter - the index to end, is not inclusive in the copy
The slice()
method can also take negative values to represent the indexes, thereby making the count start from the right of the array, with the last element having an index of -1
Bonus
The slice()
method can be used for modifying strings and it works exactly as it does on arrays. Let's take a look at a sample code:
Summary
We have taken practical steps to evaluate the splice()
and slice()
javascript array methods and their differences. We have also learned that the slice()
method works on strings too.
Moving forward, this should help us determine the best use cases for each method in our applications. Cheers!