Differences in Javascript .Slice() & .Splice() methods
If you are new in the software developer world, these two (Slice() & Splice()) methods can get pretty confusing. They both sound pretty similar, so you might think they work the same way but actually they are not. So let’s find out what each of these actually does and how they differ from each other.
.Slice()
.slice() is exactly what is sound like!
The .slice() method is used to extract a chunk (or slice) from any given array, and returns that extracted chunk into a new array. It does not modify the array on which it is called.
array.slice(from, until);
- From: Slice the array starting from an element index
- Until: Slice the array until another element index
Here is an example:
In the example above, I have an array [1,2,3,4,5,6] and on the second and fourth line I wanted the 2nd, 4th, 1st & 4th index out of the array so I used a slice method on that array, and it returned from index 2–4, meaning 3 & 4 & index 1–4, meaning 2,3,&4. Notice it did not change the original array!
Now there is a tricky part, The slice( ) method doesn’t include the last given element.
In the example above, the array does not have an index of 6 so it returned the last number in the array.
.Splice()
The .splice() method is a destructive array method, which means it modifies the array on which it is called on. It is used to alter the contents of an array by removing existing elements and/or adding new elements. It changes an array unlike .slice() method.
Removing with .splice()
array.splice(index, number of elements);
Index is the starting point for removing elements. Elements which have a smaller index number from the given index won’t be removed. If we don’t define the second parameter, every element starting from the given index will be removed from the array.
In the example above, I put a starting point index of 2, and I want to remove 2 items after that. So, I got “banana” & “kiwi” in a new array. The original array also got altered.
In the example above, I am splicing starting index 2, meaning everything starting index 2 will be removed. So I got the removed items in a new array and the original array also got altered.
Adding with .splice()
For adding elements, we need to give them as the parameters (depends on how many to add) to the splice ( ) method:
array.splice(index, number of elements, element, element);
In the example above, I took out one item, index no 2 (“banana”) from the array and replaced it with “milk” & “nuts”.
Here are the sources you can check out if you need more in depth description:
https://www.w3schools.com/jsref/jsref_splice.asp
https://www.w3schools.com/jsref/jsref_slice_array.asp
Also, try it out in your console to have a better understanding :)