Lessons · TypeScript · slice copies, splice changes
slice copies, splice cuts
slice(start, end) returns a copy of part of the array; splice(start, count) removes items from the array itself.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
One letter apart, opposite behaviour. Using splice where you meant slice mutates state that other code relies on.
How to think about it
Do I want a copy, or to cut the original? Want a piece without changing the original: slice. Want to remove or insert in place: splice. When in doubt, slice.
Worked example
const a = [1, 2, 3, 4];Four items.
a.slice(1, 3)[2, 3]; a unchanged.
a.splice(1, 2)returns [2, 3]; a is now [1, 4].
Your turn
Get everything but the first item without changing the array.
const rest = arr.(1);
Solve one with the tests running
The trap
splice's second argument is a COUNT, slice's is an END index.
Practise slice copies, splice changes on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.