AI Hints
Home›JavaScript Tutorial›Searching and Sorting
JavaScript · Lesson 47 of 138

slice and splice

Copies and changes.

⏱ 2 min read▶ Video at 57:10🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

slice and splice
From the video: slice and splice
  • 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.

app.jsjavascript
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);
Output
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.

keyvalue
slice(a, b)copy from a to b
Originalunchanged by slice
splice(i, n, ...)remove n, insert
Prefercopies

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.

app.jsjavascript
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);
Output
[ '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
Next up: Sorting — sort and its surprise