When to Use slice and splice in JavaScript
The difference between slice and splice, and which one to use.
slice and splice are one letter apart and both work with part of an array,
so they're easy to mix up. The big difference is that slice copies and
splice changes the array you call it on.
TL;DR Use slice when you want a piece of an array without changing it. Use
splice when you want to remove, replace or insert items in the original
array.
slice
array.slice(start, end) returns a new array from start up to, but not
including, end:
const fruits = ["apple", "banana", "cherry", "date", "elderberry"]fruits.slice(1, 3) // ["banana", "cherry"]fruits.slice(2) // ["cherry", "date", "elderberry"]fruits.slice(-2) // ["date", "elderberry"]fruits.slice() // a copy of the whole arrayconsole.log(fruits)// ["apple", "banana", "cherry", "date", "elderberry"]
Leave off end to go to the end of the array, and use a negative number to
count from the end. The orginal array never changes.
splice
array.splice(start, deleteCount, ...items) changes the array in place and
returns the items it removed.
Removing items:
const fruits = ["apple", "banana", "cherry", "date"]const removed = fruits.splice(1, 2)console.log(removed) // ["banana", "cherry"]console.log(fruits) // ["apple", "date"]
Inserting items by passing 0 as the deleteCount:
const fruits = ["apple", "date"]fruits.splice(1, 0, "banana", "cherry")console.log(fruits) // ["apple", "banana", "cherry", "date"]
Replacing an item by removing one and adding one in its place:
const fruits = ["apple", "banana", "cherry"]fruits.splice(1, 1, "blueberry")console.log(fruits) // ["apple", "blueberry", "cherry"]
When to Use Each
- Showing one page of results:
slice, e.g.items.slice(0, 10). - Grabbing the last few items:
slice(-3). - Removing, inserting or replacing items in an array only your code uses:
splice. - Working with data other code relies on, like state in a React component:
slice, since changing the original can cause hard to find bugs.
You can still remove an item without changing the original by combining slice
with the spread operator:
const removeAt = (array, index) => [...array.slice(0, index),...array.slice(index + 1),]const fruits = ["apple", "banana", "cherry"]removeAt(fruits, 1) // ["apple", "cherry"]console.log(fruits) // ["apple", "banana", "cherry"]
If you need the original array to stay the same, use slice. If you want to
change it, use splice.
Have some feedback on this post? .