The slice() method of the Array class in JavaScript extracts a section of the calling array and returns a new array.
There are 3 variations for the syntax of Array.slice() method. They are:
slice()
This method extracts a section of the calling array from the beginning and returns a new array.
Returns value of type Array
.
slice(start)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
start | optional | The beginning index of the section to extract. Defaults to 0. |
This method extracts a section of the calling array from the start index to the end of the array and returns a new array.
Returns value of type Array
.
slice(start, end)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
start | optional | The beginning index of the section to extract. Defaults to 0. |
end | optional | The end index of the section to extract. Defaults to the array's length. The end index is not included in the extracted section. |
This method extracts a section of the calling array from the start index to the end index (not included) and returns a new array.
Returns value of type Array
.
In JavaScript, we can use the slice() method to extract a section of an array and return a new array.
For example,
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.slice(1, 3);
console.log(slicedArr);
[2, 3]
We can use the slice() method to extract a section of an array from a specific start index to the end of the array and return a new array.
For example,
const arr = ['a', 'b', 'c', 'd', 'e'];
const slicedArr = arr.slice(2);
console.log(slicedArr);
['c', 'd', 'e']
We can use the slice() method without arguments to make a shallow copy of an array and return a new array.
For example,
const arr = [10, 20, 30];
const copiedArr = arr.slice();
console.log(copiedArr);
[10, 20, 30]
In this JavaScript tutorial, we learned about slice() method of Array: the syntax and few working examples with output and detailed explanation for each example.