The Letter P Difference, .slice() vs. .splice()

David Chung
The Startup
Published in
3 min readNov 2, 2020

--

While learning Javascript, .slice and .splice() have confused me time and time again. A single letter (p) always caused me to google what the differences were. Both methods are very important while coding in Javascript.

Let’s start with .slice(). The .slice() method copies a part of an array and returns the part that was copied as a new array. It keeps the original array intact.

array.slice(start index, end index);

  • Start index: You take a slice of the array start from this element index.
  • End index: The slice of the array until after this index.

Lets say you have an array:

We slice from “array” and assign it to “copiedArray”.

This will return:

“copiedArray” will return from index 0 to the “front” of index 4.

The original array remains untouched. Many programmers use slice to manipulate arrays as they please.

Now with .splice(). The difference between slice and splice is just one letter (in the name of the method, that is). With .splice(), the method changes the array by adding or removing elements from it. The way I remember the difference between the two, is that I think of the “P” as Pineapple. Stay with me now. If you add pineapple to a slice of pizza, you’re changing the original pie of pizza to a pineapple pizza. You’ve ruined a perfectly good cheese pizza. Whether or not you are on team pineapple on pizza or not, .splice() changes the original array by adding or removing elements from it.

When you put the P(ineapple) on the slice of pizza, you now have splice

We can remove elements by giving the method an index parameter and the number of elements to be removed.

Index is where you start removing elements from. Elements that have a smaller index number from the given index won’t be removed.

Every element starting from index 3 will be removed and will be returned.

Will return:

array now only has 1,2,3 left in the array.

When we add the second parameter:

From index 3, we remove 2 elements.

We get:

Elements 4 and 5 got removed and array now has 1,2,3,6.

We can also add elements with the .splice() method. This requires us to give it a 3rd, 4th and 5th parameters.

For example, we could add in a string in the beginning of the array without removing anything:

would return:

To summarize:

.slice()

  • Copies elements from an array and returns them as a new array
  • Does not change the original array
  • Slice doesn’t include the 2nd index parameter
  • Can be used on both strings and arrays

.splice()

  • Mutates/Changes the original array
  • Returns an array of removed elements
  • Used for adding/removing elements from the original array
  • Can only be used on arrays

Hopefully, the difference between .slice() and .splice() became a little clearer. The best way to remember these methods is to program with these methods often!

--

--