DEV Community

Cover image for Array.slice() - for slicing an array
Dillion Megida
Dillion Megida

Posted on • Updated on

Array.slice() - for slicing an array

This article is the fifth of the Array Method Series. In this article, I will explain what the slice Array method is.

What is the Slice Method?

The slice method of arrays returns a specified section of an array--a slice of the array.

This method does not modify the original array. It returns a sliced copy as a new array.

Syntax of the Slice Method

array.slice(start, end)
Enter fullscreen mode Exit fullscreen mode

The start argument specifies the index that the slicing starts from.

The end argument specifies the index that the slicing stops, but the item at this index is not returned.

If the end argument is not provided, the slice method slices from the start to the end of the array.

If both arguments are not provided, the slice method starts from the 0 index and slices to the end--basically a copy of the whole array.

Without the Slice Method

The slice method is an abstracted function that returns a section of an array cut at one or two places. Here's an example showing how you can slice an array without this method:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8]

const START_INDEX = 2

const END_INDEX = 7

const newArray = []

for (let i = START_INDEX; i < END_INDEX; i++) {
  const item = array[i]
  newArray.push(item)
}

console.log(newArray)
// [ 2, 3, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode

The for loop starts from the START_INDEX and ends one index short of the END_INDEX.

With the Slice Method

Here's how you achieve the previous result with slice:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8]

const newArray = array.slice(2,7)

console.log(newArray)
// [ 2, 3, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode

Without an end argument

The end will be the rest of the array:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8]

const newArray = array.slice(2)

console.log(newArray)
// [2, 3, 4, 5, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

Without both arguments

The start would be 0 by default, and the end would be the rest of the array:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8]

const newArray = array.slice()

console.log(newArray)
// [0, 1, 2, 3, 4, 5, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

With negative arguments

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8]

const newArray = array.slice(-3, -1)

console.log(newArray)
// [ 6, 7 ]
Enter fullscreen mode Exit fullscreen mode

Negative arguments count backward such that -1 is 8, -2 is 7, and -3 is 6.

For -3 and -1, the slice takes a cut from 6 to 8 but without 8, thereby resulting in [6,7]

Top comments (0)