Vanilla JavaScript Slice vs Splice

— 4 minute read

The other day I asked the following question on Twitter: "What are the things you always have to google as a developer?".

This was the response from Rey van den Berg.

I must admit that I've had to look up the difference between the two more than once.

JavaScript Slice permalink

To start, these are both arrays manipulating methods, but let's see at what makes the slice one unique.

The main difference is that the slice method copies a part of the original array. It does not change the original one.

var array = [1, 2, 3, 'test', 5];
var sliced = array.slice(0, 4);
// [1, 2, 3, "test"]

The two parameters we can pass to the slice method are the starting point and the endpoint. So in our example, we are stating we start at position 0 and slice till position 4.

Fun fact: Slice will also work on a string!

var string = 'Hello world';
var slicedString = string.slice(0, 5);
// Hello

JavaScript Splice permalink

Ok, yes, the names are very similar. But they do something different. The main difference for the splice method is that it will modify the existing array.

With splice, we can remove or even add elements to our initial array.

JavaScript Splice Remove permalink

Removing elements will work like this:

var array = [1, 2, 3, 'test', 5];
array.splice(0, 4);
// [5]

You see, we removed the first four elements from our array. The parameters we provided are starting and the number of elements. In this case, we start at position 0 and remove four elements.

We can also forget the second parameter. It will then remove everything after the start position we set.

var array = [1, 2, 3, 'test', 5];
// [1, 2]

JavaScript Splice Add permalink

As mentioned, we can also add elements like this:

<!-- Splice Add -->
var array = [1,2,3,'test',5];
// ["random", 1, 2, 3, "test", 5]

We told the splice to enter our new element random at position 0. We can even define multiple elements here!

You can have a play with these two methods on this Codepen.

See the Pen Vanilla JavaScript Slice vs Splice by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter