Array.splice and Array.slice in JavaScript

What's the difference?

Kunal Tandon
Developer’s Arena
3 min readJul 30, 2019

--

Photo by Artem Sapegin on Unsplash

You must have used the above functions available in JavaScript Array’s prototype. They look so similar, at times even I get confused between the two.

Key Difference

Array.splice modifies the original array and returns the array containing the elements deleted.

Array.slice does not modify the original array. It just returns a new array of elements which is a subset of the original array.

Array.splice

Splice is used to modify the content of an array which includes removing elements, replacing existing elements, or even adding new elements to an array.

Using the splice function updates the original array.

Consider the following array:

Array.splice signature:

Removing the elements

To remove elements from an array, we write:

This will delete one element, starting from index 3 and returns the deleted array. As a result, we get:

Adding new elements

To add new items to an array, we write:

At 2, this will add the numbers 100 and 101. The final values will be:

Modifying an existing element

We can cleverly modify an existing element in an array using splice so that we delete the item at an index and insert a new element in its place.

To replace 3 with 100, we write:

We get the following values for arr and arr2 after executing the above code snippet:

Array.slice

While splice can also insert and update elements of an array, the slice function is used only to remove elements from an array.

We can only delete elements from an array using the slice function

Array.slice signature

startIndex — The starting index for the sliced array we need to get with startIndex included.

endIndex (optional) — The ending index up to which the slicing is to be done, with endIndex excluded.

Consider the following array:

To get a slice of an array from values [2, 3, 4, 5], we write:

Notice that, here, we gave the second argument as 6 and not 5.

After executing the above code, we get the values as:

The variable arr remains the same after the execution of the slice statement, whereas the splice statement was updating the actual array.

So, if we want to update the original array, we use the splice function but if we only want a portion of an array, we use slice.

--

--