The slice method in JavaScript is used to extract a portion of an array into a new array. It doesn't modify the original array but returns a shallow copy of a portion of the array.
The syntax for slice is:
array.slice(start, end)
Here, start is the index at which to begin extraction, and end is the index before which to end extraction (the element at this index will not be included in the sliced array).
Slicing from a Starting Index
In this example, slice(1) starts at index 1 (which is the second element, 'banana') and goes to the end of the array, creating a new array with all the elements starting from 'banana'.
let fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']; let slicedFruits = fruits.slice(1); // Result: ['banana', 'cherry', 'date', 'elderberry', 'fig']
Slicing with a Range
This time, slice(1, 4) starts at index 1 ('banana') and ends at index 4 ('date'). The element at index 4 ('date') is not included in the result.
let fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']; let slicedFruits = fruits.slice(1, 4); // Result: ['banana', 'cherry', 'date']
Copying the Whole Array
By calling slice() without arguments, it copies the entire array, essentially creating a new array with the same elements.
let fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']; let slicedFruits = fruits.slice(); // Result: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
Using Negative Indices
Using negative indices counts from the end of the array. -1 refers to the last element, -2 refers to the second-to-last element, and so on.
let fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']; let slicedFruits = fruits.slice(-2); // Result: ['elderberry', 'fig']
Slicing with Negative and Positive Indices
Here, slice(1, -2) starts at index 1 ('banana') and ends at the second-to-last element ('date'), excluding the last two elements ('elderberry' and 'fig').
let fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']; let slicedFruits = fruits.slice(1, -2); // Result: ['banana', 'cherry', 'date']