slice vs splice

Working with arrays in JavaScript is a fairly common task and the language provides us developers with a myriad of methods. We can iterate through arrays, push elements, pop values (remove and return the last element) and slice and dice the array as we see fit.

Personally, I always mix-up two array methods in particular: slice and splice. Their functionality is very similar, however there are some critical differences between the two.

slice

Let's start with the slice() method first. The signature specifies two optional parameters:

slice(start, end)

With slice() we can return a so called shallow copy of an array based on the start and 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:

See the Pen slice by Cloudinary (@Cloudinary) on CodePen.

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

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)

Where the 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 (itemN).

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.

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.

See the Pen splice by Cloudinary (@Cloudinary) on CodePen.