JavaScript Array Methods: .splice() vs .slice()

Betsy Sallee
5 min readAug 25, 2018

--

When it comes to operating on arrays, .splice() and .slice() are two incredibly useful methods to have in your toolkit. It’s not always easy, though, to remember which is which. I’ve put together this crash course on the ins-and-outs of each so that you can start splicing and slicing with confidence. I’ve also included two solutions to the common chunking algorithm: one makes use of .splice(), and the other makes use of .slice().

Onwards!

.splice()

The .splice() method is a destructive array method, which means it modifies the array on which it is called (disclaimer: destructive methods can be risky, especially if you use the array in question elsewhere in your program, so proceed with caution). It is used to alter the contents of an array by removing existing elements and/or adding new elements. The return value of .splice() will always be an array of any items that were removed.

The first argument, which is required, indicates the index in the array at which to begin adding or removing elements. You can pass in a negative value as this argument if you’d like to start at the end of the array.

The second argument is optional, but if it’s provided, it specifies the number of elements to remove from the array. If it is set to 0, no items will be removed, but if it is omitted entirely, all elements beginning at the specified index (i.e. the value passed as the first argument) will be removed.

Any subsequent arguments are optional, but if they’re present, they indicate the elements to add to the array. These elements will be inserted immediately before the starting index (again, this is the value passed as the first argument).

Let’s see .splice() in action, taking note of the destructive nature of this method:

let daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]console.log(daysOfTheWeek.splice(4, 2)) 
//=> [ 'Friday', 'Saturday' ]
console.log(daysOfTheWeek)
//=> [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Sunday' ]
let monthsOfTheYear = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]console.log(monthsOfTheYear.splice(4))
//=> [ 'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December' ]
console.log(monthsOfTheYear)
//=> [ 'January', 'February', 'March', 'April' ]

let programmingLanguages = ["JavaScript", "Ruby", "Python"]
console.log(programmingLanguages.splice(2, 0, "C++", "C#"))
//=> []
console.log(programmingLanguages)
//=> [ 'JavaScript', 'Ruby', 'C++', 'C#', 'Python' ]
let seasons = ["Spring", "Summer", "Fall", "Winter"]console.log(seasons.splice(-2)
//=> [ 'Fall', 'Winter' ]
console.log(seasons)
//=> [ 'Spring', 'Summer' ]

.slice()

The .slice() method is used to extract a chunk (or slice) from any given array, and unlike .splice(), it does not modify the array on which it is called.

The first argument of .slice() is required, and it indicates the index at which to begin the extraction. As with .splice(), you can pass a negative value for this argument if you’d like to begin your slice at the end of the array.

The second argument is optional, but if it’s included, it specifies the index at which to end the slice. It’s important to note that your slice will not include the element at the index you pass in for this argument; the slice will consist of all elements from the starting index (i.e. the value passed in as the first argument) up to (but not including) the ending index (i.e. the value passed in as the second argument). Again, you can use negative integers if you’d like to count backwards from the end of the array. And finally, if you choose to omit the second argument, your slice will go from the starting index until the end of the array.

Here are some examples of .slice() at work:

let daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]console.log(daysOfTheWeek.slice(2, 4)) 
//=> [ 'Wednesday', 'Thursday' ]
console.log(daysOfTheWeek)
//=> [ 'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday' ]
console.log(daysOfTheWeek.slice(-1))
//=> [ 'Sunday' ]
console.log(daysOfTheWeek)
//=> [ 'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday' ]
console.log(daysOfTheWeek.slice(3))
//=> [ 'Thursday', 'Friday', 'Saturday', 'Sunday' ]
console.log(daysOfTheWeek)
//=> [ 'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday' ]
console.log(daysOfTheWeek.slice(-3, -2))
//=> [ 'Friday' ]
console.log(daysOfTheWeek)
//=> [ 'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday' ]

The Chunking Algorithm

I first encountered the chunking algorithm in Stephen Grider’s fabulous Udemy course entitled “The Coding Interview Bootcamp: Algorithms + Data Structures” (I can’t recommend this course highly enough). The challenge is to write a function which, when given an array and chunk size, will divide the array into subarrays, where each subarray is of length size. For example:

chunk([1, 2, 3, 4], 2)
//==> [[ 1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2)
//==> [[ 1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3)
//==> [[ 1, 2, 3], [4, 5, 6], [7, 8]]

I first solved this problem using the .splice() method, as such:

function chunk(array, size) {
let newArray = []
while (array.length > 0) {
newArray.push(array.splice(0, size))
}
return newArray;
}

Let’s walk through that solution step by step. I’ve started off by setting up a variable called newArray that is pointing to an empty array. Next, I’ve launch into a while loop that will continue to execute so long as the length of the original array is greater than 0. This while loop works because, inside of the loop, I’m modifying the original array with the .splice() method, to which I’m passing two arguments: 0, and size. So, each time through the while loop, I’m adding a new element (which is an array) to newArray, and modifying the original array in the process. It is the destructive nature of .splice() that enables me to pass 0 as the first argument; the element at index 0 is always changing because, each time through the loop, we’re shuffling all of the elements closer and closer to the proverbial chopping block. When the original array is finally empty, we break out of the loop and return newArray.

This solution is concise, but as I mentioned, .splice() can be risky. What would happen if I needed to use the same array elsewhere in my program, only to find that it had been spliced away? Suffice it to say, I would be in trouble.

There is, however, a similar solution to this problem that makes use of the nondestructive .slice() method. Let’s take a look:

function chunk(array, size) {
let newArray = []
let index = 0
while (index < array.length) {
newArray.push(array.slice(index, index + size));
index += size;
}
return newArray;
}

Once again, we’ve set up a variable called newArray that points to an empty array. We’ve also set up a variable index, which is initialized as 0. And, as in the first solution, we jump into a while loop, but this time, the while loop will continue executing as long as the value of index is less than the length of the original array. Next, we start pushing slices from the original array (which are themselves arrays) into newArray, and then increment index by the value of size. So, each time through the while loop, we’re taking a slice from the original array that begins at a new index, but the length of that slice will always be the same size.

Conclusion

I hope this post has shed some light on the intricacies of both .splice() and .slice(). In terms of remembering which is which, I tend to think of the “p” in the word “splice” as representing “permanent,” because .splice() permanently modifies the array on which it is called.

Happy s(p)licing!

--

--