Skip to main content

Command Palette

Search for a command to run...

How does the JavaScript slice() method work?

Updated
1 min read
How does the JavaScript slice() method work?

The slice() method** returns the selected items** of an array, but it won't mutate the original array. That's a difference with the splice() method.

slice() receives two parameters:

  1. The starting index to remove

  2. The end index (it won't be removed)

Let's see an example:

const numbers = [1,2,3,4,5]

const removedValues = numbers.slice(0,2)

removedValues // [ 1, 2 ]
numbers // [ 1, 2, 3, 4, 5 ]

We have the numbers array with five values. Then we use the slice() method to remove some. We set as a first parameter the starting index to remove as zero, because we want to start removing from the value 1 of the list. Then we set a 2 as a second parameter because we want to stop our removal at the index position 2. That means that position value won't be included, so the value 3 won't be part of the removed values.

Then slice() will return the removed values, in this case will return the 1 and 2 values. The interesting thing here is that the original array is not modified. Unlike splice(), slice() doesn't mutate the original array.

More from this blog

Mario Barceló

8 posts

💻 Frontend Developer. 📱 Tech passionate. 🎲 Board Game lover. 🏈 Football rookie.