DEV Community

Cover image for Vanilla JavaScript Slice vs Splice
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript Slice vs Splice

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.

The difference between splice and slice 😂

— Rey van den Berg (@reythedev) May 28, 2020

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

JavaScript Slice

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);
console.log(sliced);
// [1, 2, 3, "test"]
Enter fullscreen mode Exit fullscreen mode

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);
console.log(slicedString);
// Hello
Enter fullscreen mode Exit fullscreen mode

JavaScript Splice

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

Removing elements will work like this:

var array = [1, 2, 3, 'test', 5];
array.splice(0, 4);
console.log(array);
// [5]
Enter fullscreen mode Exit fullscreen mode

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];
array.splice(2);
console.log(array);
// [1, 2]
Enter fullscreen mode Exit fullscreen mode

JavaScript Splice Add

As mentioned, we can also add elements like this:

<!-- Splice Add -->
var array = [1,2,3,'test',5];
array.splice(0,0,'random');
console.log(array);
// ["random", 1, 2, 3, "test", 5]
Enter fullscreen mode Exit fullscreen mode

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!

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

Top comments (0)