slice and splice
Copies and changes.
Two methods with nearly the same name do very different things. Slice copies part of an array, and leaves the original alone. Splice changes the original array, removing or inserting items.

- Similar names
- slice copies
- splice changes
Copy or change
Slice one to three copies the items from index one, up to, but not including, index three. The original is unchanged. Splice one, two removes two items starting at index one, and returns them. It can also insert new items in their place. Run it.
const letters = ["a", "b", "c", "d", "e"];
const part = letters.slice(1, 3);
console.log("slice:", part, "original:", letters);
const removed = letters.splice(1, 2, "X");
console.log("splice removed:", removed);
console.log("now:", letters);slice: [ 'b', 'c' ] original: [ 'a', 'b', 'c', 'd', 'e' ] splice removed: [ 'b', 'c' ] now: [ 'a', 'X', 'd', 'e' ]
Remembering which is which
One way to remember. Splice has a P for, it changes the array in Place. When you're not sure, prefer slice, and other methods that make copies. Code that doesn't change data in surprising places is much easier to debug.
| key | value |
|---|---|
| slice(a, b) | copy from a to b |
| Original | unchanged by slice |
| splice(i, n, ...) | remove n, insert |
| Prefer | copies |
Copying without changing
Modern JavaScript has methods that return a changed copy, and leave the original alone. To spliced is the copy version of splice. And with replaces one item in a copy. These are handy when you must not change the original array, like in React. Run it.
const colours = ["red", "green", "blue"];
const fewer = colours.toSpliced(1, 1);
const changed = colours.with(0, "pink");
console.log(fewer);
console.log(changed);
console.log(colours);[ 'red', 'blue' ] [ 'pink', 'green', 'blue' ] [ 'red', 'green', 'blue' ]
Summary
Slice copies a part of an array, and splice changes the array itself. Next, sorting, and its famous surprise.
Key takeaways- slice copies
- splice changes
- Prefer copies