What is the difference between slice and splice?
slice copies a section into a new array and leaves the original alone. splice changes the original array in place by removing, replacing or inserting items, and returns the removed items.
Explain it simply
slice is like photocopying pages 2 and 3 of a notebook: the notebook stays intact and you get new pages. splice is like tearing pages out or stapling new ones in: the notebook itself changes.
slice(start, end)returns items fromstartup to but not includingend.splice(start, deleteCount, ...itemsToInsert)edits the array and returns what it removed.
A memory trick: the extra letter p in splice stands for "permanent change".
Example
const arr = [1, 2, 3, 4, 5];
console.log(arr.slice(1, 3)); // Output: [2,3]
console.log(arr); // Output: [1,2,3,4,5]
console.log(arr.splice(1, 2)); // Output: [2,3]
console.log(arr); // Output: [1,4,5]
arr.splice(1, 0, "x"); // insert at index 1, delete nothing
console.log(arr); // Output: [1,"x",4,5]What to say in the interview
"slice is non-mutating and takes start and an exclusive end. splice mutates the array: it removes deleteCount items at an index, optionally inserts new ones, and returns the removed items. I use slice to copy and splice when I really need in-place edits."
Common mistakes
- Treating the second argument of splice as an end index. It is a delete count.