slice vs splice
Older Article
This article was published 5 years ago. Some information may be outdated or no longer applicable.
Working with arrays in JavaScript is a daily affair. The language gives us a pile of methods: iterating, pushing elements, popping values, chopping arrays up however we like.
Two methods I personally mix up every single time: slice and splice. They sound alike, they look alike, but they behave differently in ways that matter.
slice
Let’s start with slice(). Its signature takes two optional parameters:
slice(start, end)
slice() returns a shallow copy of an array based on the start and end parameters, which are index positions. The element at end is not included in the result. And slice() won’t touch the original array:
See the Pen slice by Cloudinary (@Cloudinary) on CodePen.
Shallow copy means we copy a reference to a new variable using the assignment operator (
=). Because it’s a reference, updating values in the original also updates the copy. Deep copy, by contrast, creates a separate memory location, so changes to the original don’t bleed through.
slice() hands you a new array with the extracted elements, as shown in the embedded example above.
splice
splice() has a different signature, and it does modify the original array by removing and/or replacing elements.
splice(start, count, ...itemN)
start is mandatory. The others are optional. start is the index where the modification begins. Interestingly, if this value exceeds the array’s length, splice() acts as a pure add operation, appending any itemN elements.
count tells the method how many elements to delete, starting from start. If you leave it out, the deletion runs with array.length - start. Passing 0 or a negative number skips deletion, but you can still add new elements via itemN.
itemN specifies elements to insert at the start position. Leave it out and splice() just removes elements.
A few examples below. Remember that splice() mutates the original array, so run each section independently.
See the Pen splice by Cloudinary (@Cloudinary) on CodePen.