slice = copy
slice returns a shallow copy of a portion of the array.
It does not modify the original array.
JavaScript Tutorial
slice copies part of an array without changing it, while splice edits the array in place.
Knowing the difference prevents mutation bugs.
Many bugs come from unintentional array mutation.
Choosing the right method keeps your data flow predictable.
array.slice(start, end)
array.splice(start, deleteCount, ...items)const items = ["a", "b", "c", "d"];
const part = items.slice(1, 3);
console.log(part); // ["b", "c"]
console.log(items); // unchangedslice copies without mutation.
const items = ["a", "b", "c", "d"];
items.splice(1, 2);
console.log(items); // ["a", "d"]splice removes items in place.
slice returns a shallow copy of a portion of the array.
It does not modify the original array.
splice removes or inserts items in place.
It mutates the original array.
Use slice when you want immutability.
Use splice when you must update the array itself.
const items = ["a", "d"];
items.splice(1, 0, "b", "c");
console.log(items); // ["a", "b", "c", "d"]splice can insert items.
const items = ["a", "b", "c", "d"];
const lastTwo = items.slice(-2);
console.log(lastTwo); // ["c", "d"]Negative indexes count from the end.
Without
const items = [1, 2, 3];
items.splice(1, 1); // mutatesWith
const items = [1, 2, 3];
const copy = items.slice(1, 2); // no mutationUse splice to change the original array.
Use slice to copy instead of mutate.
splice returns the removed elements, not the array.
slice copies, splice mutates.
An array of removed elements.
When you want immutability.
Practice: Remove the middle element from an array using splice.
const nums = [1, 2, 3, 4, 5];
// TODO: remove 3
One Possible Solution
const nums = [1, 2, 3, 4, 5];
nums.splice(2, 1);
console.log(nums);No, slice returns a new array.
Yes, splice changes the original array.
Yes, it can do both in one call.
Try editing the indexes to see how results change.