The slice() method in JavaScript is used to extract a section of an array and returns a new array. This method does not modify the original array but instead returns a shallow copy of a portion of the array.
Syntax
array.slice(start, end);
Parameters
Parameters | Descriptions |
---|---|
start (Optional) | The zero-based index at which to begin extraction. If start is undefined, slice starts from index 0. If start is negative, it indicates an offset from the end of the sequence. -2 means the last two elements. |
end (Optional) | The zero-based index before which to end extraction. The slice method extracts up to but not including end. If end is omitted, slice extracts through the end of the sequence. If end is negative, it indicates an offset from the end of the sequence. -2 means before the last two elements. |
Return Value
Return Type | Description |
---|---|
Array | A new array containing the extracted elements. |
Example 1: Extracting a Portion of an Array
This code demonstrates how to use the slice()
method to extract a portion of an array.
let Arr = [ 10, 20, 30, 40, 50 ]; let selectedItems = Arr.slice(1, 4); console.log('Selected Items:', selectedItems); console.log('Original Array:', Arr);
Output:
Selected Items: [ 20, 30, 40 ]
Original Array: [ 10, 20, 30, 40, 50 ]
Example: Using Negative Indexes
Negative indexes can be used to slice elements from the end of the array.
let Arr = [ 10, 20, 30, 40, 50 ]; let selectedItems = Arr.slice(-3, -1); console.log('Selected Items:', selectedItems); console.log('Original Array:', Arr);
Output:
Selected Items: [ 30, 40 ]
Original Array: [ 10, 20, 30, 40, 50 ]
Note
The slice()
method does not change the original array but returns a new array. It returns a shallow copy, so modifying the new array will not affect the original array, and vice versa.
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |