JavaScript Arrays: slice vs splice
In JavaScript, it is easy to confuse slice
and splice
. I certainly do it all the time. They have similar names but act in very different ways. Here’s a quick guide to keep them straight.
tl;dr
slice()
returns up to but not including the second argument;splice()
does return the second argumentslice()
returns a new array object;splice()
mutates the original array objectslice()
can take up to 2 arguments;splice()
can taken
arguments
Difference #1: Returns
The most noticeable difference is that the slice()
method returns up to but not including the second argument, whereas splice()
returns up to the second argument.
['a', 'b', 'c', 'd', 'e'].slice(1,3)
// ["b", "c"]
['a', 'b', 'c', 'd', 'e'].splice(1,3)
// ["b", "c", "d"]
Difference #2: Mutability
Under-the-hood something much more fundamental is going on with the method returns. slice()
creates a brand new array object which it then returns; by contrast, splice()
mutates the original array object and returns it.
const arr = ['a', 'b', 'c', 'd', 'e']
arr.slice(1,3)
// ["b", "c"]
arr
// ['a', 'b', 'c', 'd', 'e']
const arr2 = ['a', 'b', 'c', 'd', 'e']
arr2.splice(1,3)
// ["b", "c", "d"]
arr2
// ["a", "e"]
Difference #3: Number of arguments
slice()
can take either 1 argument, which acts as the begin
or 2 arguments which represent begin
and end
.
// array.slice(begin)
// array.slice(begin, end)
['a', 'b', 'c', 'd', 'e'].slice(1)
// ["b", "c", "d", "e"]
['a', 'b', 'c', 'd', 'e'].slice(1,3)
// ["b", "c"]
For splice()
, 1 argument acts as the start
and a 2nd argument is formally the deleteCount
, the number of the old array element to be removed.
// array.splice(start)
// array.splice(start, deleteCount)
['a', 'b', 'c', 'd', 'e'].splice(1)
// ["b", "c", "d", "e"]
['a', 'b', 'c', 'd', 'e'].splice(1,3)
// ["b", "c", "d"]
But splice()
can ultimately take n
arguments, as each successive argument after the 2nd is treated as an item to add to the array beginning at the start
index (ie argument 1).
const arr = ['a', 'b', 'c', 'd', 'e']
arr.splice(0, 1, 'dog')
// ["a"]
arr
// ["dog", "b", "c", "d", "e"]
Further Reading
As usual, MDN is the canonical source for a more in-depth discussion of slice()
and splice()
.
Other than the differences listed above, the two methods are the same and you can use them interchangeably as you feel fit :)
Want to improve your JavaScript? I have a list of recommended JavaScript books.