JavaScriptEasy
Difference between slice() and splice()?
slice(start, end) returns a copy of part of an array without changing it; splice(start, deleteCount, ...items) changes the original array in place by removing and/or inserting items, and returns the removed ones.
slice | splice | |
|---|---|---|
| Mutates original | No | Yes |
| Returns | New array with the selected part | Array of removed items |
end / count | End index (exclusive) | How many items to remove |
| Also on strings | Yes ("hello".slice(1, 3)) | No |
slice details
- Negative indexes count from the end:
arr.slice(-2)gives the last two items. arr.slice()with no arguments makes a shallow copy.
splice details
- Remove:
arr.splice(1, 2)removes two items starting at index 1. - Insert:
arr.splice(1, 0, "x")inserts without removing. - Replace:
arr.splice(1, 1, "x")swaps one item.
Immutable alternative: toSpliced (ES2023)
arr.toSpliced(1, 1, "x") does what splice does but returns a new array and leaves the original alone. This is what you want for React state, where mutating with splice would not trigger a re-render.
Memory trick
splice = changes in place.
Code example
js
1const letters = ["a", "b", "c", "d", "e"];23// slice: copy part of the array, original unchanged4console.log(letters.slice(1, 3)); // ["b", "c"]5console.log(letters.slice(-2)); // ["d", "e"]6console.log(letters); // ["a", "b", "c", "d", "e"]78// splice: modifies in place, returns removed items9const removed = letters.splice(1, 2); // remove 2 items at index 110console.log(removed, letters); // ["b", "c"] ["a", "d", "e"]1112letters.splice(1, 0, "x", "y"); // insert without removing13console.log(letters); // ["a", "x", "y", "d", "e"]1415letters.splice(-1, 1, "z"); // replace the last item16console.log(letters); // ["a", "x", "y", "d", "z"]1718// Immutable splice for state updates19const todos = ["write", "test", "ship"];20const withoutTest = todos.toSpliced(1, 1);21console.log(withoutTest, todos); // ["write", "ship"] ["write", "test", "ship"]2223// slice works on strings too24console.log("JavaScript".slice(0, 4)); // Java
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.