Personally, I always mix-up two array methods in particular:
splice. Their functionality is very similar, however there are some critical differences between the two.
Let's start with the
slice() method first. The signature specifies two optional parameters:
slice() we can return a so called shallow copy of an array based on the
end parameters, which are essentially index locations. Please note that the index specified at
end is not included in the new array. Also note that
slice() will not modify the original array:
Shallow copy is when we copy a reference variable to a new variable using the variable assignment operator (
=). That means that since we are working with a reference, updating the values in the original assignment will also update the reference. Another term to understand is deep copy, which, unlike the previously mentioned shallow copy, does create a separate memory location and therefore an update to the original assignment will not update the reference.
slice() returns a new array containing the elements extracted, as also seen above in the embedded environment.
Splice on the other hand has a slightly different signature and it does modify the original array by removing and/or replacing elements in it.
splice(start, count, ...itemN)
start is a mandatory parameter, the others are optional.
start is an index location representing where to start the modification of the array. Interestingly enough, if this value is greater than the length of the array, the operation will work as an add operation adding any number of items to the array (
count is a delete counter - indicating how many elements to remove from the array. This delete operation will start the deletion process from
start index. If this value is missing - which is perfectly fine since it's optional - the deletion will use the result of
array.length - start. Adding
0 or a negative number is also possible for the
count parameter, but in that case new elements would be added and this works in conjunction with
itemN speicifes any number of elements that will be added to the array after the location specified by
start. This parameter is also optional, failing to provide any values will indicate to
splice() to remove elements from the array instead.
A few examples can be seen below - please remember that
splice() does modify the original array so run the sections individually.