The names are almost the same, and the behaviour is very different.
slice | splice | |
|---|---|---|
| Changes the original array | No | Yes |
| Returns | a new array with the copied part | an array of the removed items |
slice(start, end)
Copies from start up to, but not including, end. The original is untouched.
const letters = ["a", "b", "c", "d", "e"];
console.log(letters.slice(1, 3)); // → ["b", "c"]
console.log(letters.slice(2)); // → ["c", "d", "e"]
console.log(letters.slice(-2)); // → ["d", "e"]
console.log(letters.slice()); // → ["a", "b", "c", "d", "e"] (a shallow copy)
console.log(letters); // → ["a", "b", "c", "d", "e"] (unchanged)
slice() is how you take the first few items, for example for pagination, or make a quick copy of an array.
splice(start, deleteCount, …items)
Removes deleteCount items from start, optionally inserts new ones in their place, and returns the removed items. It changes the array.
const letters = ["a", "b", "c", "d", "e"];
const removed = letters.splice(1, 2); // remove 2 items from index 1
console.log(removed); // → ["b", "c"]
console.log(letters); // → ["a", "d", "e"]
letters.splice(1, 0, "X", "Y"); // insert, delete nothing
console.log(letters); // → ["a", "X", "Y", "d", "e"]
letters.splice(0, 1, "A"); // replace one item
console.log(letters); // → ["A", "X", "Y", "d", "e"]
Removing one item by value
const tags = ["html", "css", "js"];
const index = tags.indexOf("css");
if (index !== -1) {
tags.splice(index, 1);
}
console.log(tags); // → ["html", "js"]
For a version that does not mutate, use filter:
const tags = ["html", "css", "js"];
const withoutCss = tags.filter(tag => tag !== "css");
console.log(withoutCss); // → ["html", "js"]
console.log(tags); // → ["html", "css", "js"]
A newer non-mutating version
ES2023 added toSpliced(), which returns a changed copy instead of changing the original. See Changing Arrays Without Mutating Them.
slice and splice mix-ups
slice is “a slice of the pie” (a copy), splice splices the array together or apart (an edit).