Slicing and Splicing

Grade 7, page 7 of 14. A one-minute read.

These two methods have almost the same name, which is deeply unfair, because they do very different things.

slice: take a photocopy

slice(start, end) copies a section of the array into a new array, from start up to, but not including, end. The original array is left untouched:

JavaScript
const letters = ["a", "b", "c", "d", "e"];

const middle = letters.slice(1, 4);
const fromTwo = letters.slice(2);
const lastTwo = letters.slice(-2);

console.log(middle);
console.log(fromTwo);
console.log(lastTwo);
console.log(letters);

It prints

[ 'b', 'c', 'd' ]
[ 'c', 'd', 'e' ]
[ 'd', 'e' ]
[ 'a', 'b', 'c', 'd', 'e' ]

splice: perform surgery

splice(start, deleteCount, ...newItems) changes the original array. It removes deleteCount items starting at start, and optionally inserts new items in their place:

JavaScript
const colors = ["red", "green", "blue", "yellow"];

// remove 1 item at index 1
colors.splice(1, 1);
console.log(colors);

// at index 1, remove 0 items, and insert "purple" and "orange"
colors.splice(1, 0, "purple", "orange");
console.log(colors);

// at index 0, remove 2 items, and insert "pink"
colors.splice(0, 2, "pink");
console.log(colors);

It prints

[ 'red', 'blue', 'yellow' ]
[ 'red', 'purple', 'orange', 'blue', 'yellow' ]
[ 'pink', 'orange', 'blue', 'yellow' ]
TipSlice vs splice

Slice is a photocopy: it copies part of the array and leaves the original alone. Splice is surgery: it cuts and stitches the original array itself. If you're ever unsure, ask yourself: "Do I want to change the original?" No → slice. Yes → splice.

A common use of splice is removing a specific item. Find its index with indexOf, then splice it out:

JavaScript
const chores = ["wash dishes", "sweep", "do homework", "feed the goat"];

const index = chores.indexOf("sweep");
if (index !== -1) {
  chores.splice(index, 1);
}

console.log(chores);

It prints

[ 'wash dishes', 'do homework', 'feed the goat' ]

Why check index !== -1 first? Because if the item isn't in the array, indexOf gives -1, and splice(-1, 1) would remove the last item instead. Buggsy would love that.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning