These two methods have almost the same name, which is deeply unfair, because they do very different things.
slice: take a photocopy
slice(start, end) copies a section of the array into a new array, from start up to, but not including, end. The original array is left untouched:
const letters = ["a", "b", "c", "d", "e"];
const middle = letters.slice(1, 4);
const fromTwo = letters.slice(2);
const lastTwo = letters.slice(-2);
console.log(middle);
console.log(fromTwo);
console.log(lastTwo);
console.log(letters);
It prints
[ 'b', 'c', 'd' ] [ 'c', 'd', 'e' ] [ 'd', 'e' ] [ 'a', 'b', 'c', 'd', 'e' ]
splice: perform surgery
splice(start, deleteCount, ...newItems) changes the original array. It removes deleteCount items starting at start, and optionally inserts new items in their place:
const colors = ["red", "green", "blue", "yellow"];
// remove 1 item at index 1
colors.splice(1, 1);
console.log(colors);
// at index 1, remove 0 items, and insert "purple" and "orange"
colors.splice(1, 0, "purple", "orange");
console.log(colors);
// at index 0, remove 2 items, and insert "pink"
colors.splice(0, 2, "pink");
console.log(colors);
It prints
[ 'red', 'blue', 'yellow' ] [ 'red', 'purple', 'orange', 'blue', 'yellow' ] [ 'pink', 'orange', 'blue', 'yellow' ]
Slice is a photocopy: it copies part of the array and leaves the original alone. Splice is surgery: it cuts and stitches the original array itself. If you're ever unsure, ask yourself: "Do I want to change the original?" No → slice. Yes → splice.
A common use of splice is removing a specific item. Find its index with indexOf, then splice it out:
const chores = ["wash dishes", "sweep", "do homework", "feed the goat"];
const index = chores.indexOf("sweep");
if (index !== -1) {
chores.splice(index, 1);
}
console.log(chores);
It prints
[ 'wash dishes', 'do homework', 'feed the goat' ]
Why check index !== -1 first? Because if the item isn't in the array, indexOf gives -1, and splice(-1, 1) would remove the last item instead. Buggsy would love that.