Getting to Know JS: slice vs splice

If you’ve been coding in JavaScript for some time now, you’ve likely run into both slice and splice. Do you know the differences? Do you know when to use one over the other? They both seemingly do the same thing, but there are some key differences between the two. Let’s take a deeper dive into slice and splice.

slice vs splice Basics

Both slice and splice are functions on the Array’s prototype object.

Array.prototype.splicesplice(start, deleteCount, item1)
splice changes the original item it was called on. It’s good for removing or adding (or both) at a specific Array index. The first start argument is the index of the array to start at. deleteCount is the number of items to delete and the optional item1 parameter is the items you want added at the start index.

const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
let newAlphabet = alphabet.splice(2, 1);
console.log(alphabet) // ["a","b","d","e","f","g"]
// Removed 1 item at index 2 which was "c".

const missingAlphabet = ["a","b","d","e","f","g"]
missingAlphabet.splice(2, 0, "c")
console.log(missingAlphabet) // ["a","b","c","d","e","f","g"]
// Add "c" back at index 2

Notice that the original array alphabet was modified despite being saved to the newAlphabet variable. Overall, splice is useful if you want to add or remove items of the original array. What if we only want a copy of the array? That’s where slice comes in.

Array.prototype.sliceslice(start, end)
Unlike splice, slice cannot add elements to an Array. What it does instead is return a new copy of a new Array. You can slice the Array at any point or even return the whole Array as a new copy. Let’s see some examples.

const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
const newAlphabet = alphabet.slice(0,3)
console.log(newAlphabet) // ["a","b","c"]

const alphabetSecondHalf = alphabet.slice(alphabet.length/2, alphabet.length)
console.log(alphabetSecondHalf) // ["f","g","h","i","j","k"]

console.log(alphabet) // ["a","b","c","d","e","f","g","h","i","j","k"]

Notice how we made two copies of the alphabet Array but the original variable remains unaffected. slice makes a shallow copy of the original Array.

When to Use splice or slice

Since splice mutates the original Array, you’ll want to use slice whenever you need to modify an existing Array by adding or removing items. slice is good for getting information out of an Array and performing operations on that result. If you weren’t sure of the differences before, I hope this cleared some things up!

Comments