The Array.slice()
method is a built-in JavaScript function that creates a shallow copy of a portion of an array into a new array. The selected portion is determined by the start and end indices. It does not modify the original array and is commonly used for extracting parts of an array or creating duplicates.
Syntax
arr.slice(start, end);
Parameters
Parameter | Description |
---|---|
start | (Optional) The index at which to begin extraction. Defaults to 0 if not specified. |
end | (Optional) The index before which to end extraction. The element at this index is not included. Defaults to the array’s length if not specified. |
Return Value
The slice()
method returns a new array containing the selected elements. The original array remains unchanged.
Example 1: Extracting a Portion of an Array
let arr = [10, 20, 30, 40, 50]; let slicedArr = arr.slice(1, 3); console.log(slicedArr); // Output: [ 20, 30 ] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
Example 2: Using Negative Indices
let arr = [10, 20, 30, 40, 50]; let slicedArr = arr.slice(-3, -1); console.log(slicedArr); // Output: [ 30, 40 ]
Negative indices count backward from the end of the array. Here, -3
refers to cherry
and -1
refers to elderberry
(not included).
Example 3: Omitting the end
Parameter
let arr = [10, 20, 30, 40, 50]; let slicedArr = arr.slice(2); console.log(slicedArr); // Output: [ 30, 40, 50 ]
If the end
parameter is omitted, the method extracts elements from the start
index to the end of the array.
Example 4: Using slice()
to Clone an Array
let arr = [10, 20, 30, 40, 50]; let cloneArr = arr.slice(); console.log(cloneArr); // Output: [ 10, 20, 30, 40, 50 ] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
The slice()
method creates a shallow copy of the entire array when no parameters are provided.
Example 5: Combining with Other Methods
let arr = [10, 20, 30, 40, 50]; let reversedSlice = arr.slice(1, 4).reverse(); console.log(reversedSlice); // Output: [40, 30, 20] console.log(arr); // Output: [10, 20, 30, 40, 50]
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |