# slice method

The `slice` method slices and returns the specified portion of an array. The array itself remains unmodified.

The first parameter specifies the number of the array element where the cutting starts, and the second parameter is the number of the element where the cutting ends (the element with this number will not be included in the cut part). The second parameter is optional. If it is not specified, the subarray will be taken from the element specified in the first parameter to the end of the array.

It can also take negative values. In this case, the element where the cutting ends is counted from the end of the array. The last element in this case will have the number `-1`.

## Syntax

`array.slice(where to start, [where to end]);`

## Example

Let's slice array elements from zero to the second, not inclusive (the second one will not be cut out):

`let arr = ['a', 'b', 'c', 'd', 'e']; let sub = arr.slice(0, 2); console.log(sub);`

The code execution result:

`['a', 'b']`

## Example

Let's cut the elements from the first to the end of an array. To do this, we don't set the second parameter:

`let arr = ['a', 'b', 'c', 'd', 'e']; let sub = arr.slice(1); console.log(sub);`

The code execution result:

`['b', 'c', 'd', 'e']`

## Example

Let's cut out the elements from the second to the second to last (`-1` points to the second to last element and it will not be included in the extracted part):

`let arr = ['a', 'b', 'c', 'd', 'e']; let sub = arr.slice(1, -1); console.log(sub);`

The code execution result:

`['b', 'c', 'd']`

The advantage of this method is that the cut will always be part of an array, not including the last element, regardless of the size of the array.

## See also

- the `splice` method
  that also cuts off parts of an array, while changing the array itself
- the `shift` method
  that removes the first element of an array
- the `pop` method
  that removes the last element of an array

← →
↑
en ru