Array.slice()
The Array.slice()
method in JavaScript is used to create a shallow copy of a portion of an array into a new array. The original array remains unmodified. The method selects elements from the starting index to (but not including) the ending index.
Syntax
slice()
slice(start)
slice(start, end)
Parameters
Parameter | Description |
---|---|
start | The index at which to begin extraction. If omitted, the slice starts from the beginning of the array. |
end | The index before which to end extraction. If omitted, slicing continues until the end of the array. The end is not included in the extracted portion. |
Return Value
The slice()
method returns a new array containing the selected elements from the original array. The original array remains unchanged.
Examples
1. Using slice()
Without Parameters
When called without parameters, slice()
creates a shallow copy of the entire array.
const numbers = [1, 2, 3, 4, 5];
const result = numbers.slice();
console.log(result);
Output
[1, 2, 3, 4, 5]
The original array numbers
remains unchanged, and the method returns a new array with the same elements.
2. Slicing a Portion of the Array
By specifying the start
and end
indices, you can extract a portion of the array. The end
index is not included.
const numbers = [1, 2, 3, 4, 5];
const result = numbers.slice(1, 4);
console.log(result);
Output
[2, 3, 4]
The method selects elements from index 1
to 3
(not including index 4
).
3. Using Negative Indices
Negative indices can be used to count from the end of the array. For example, -1
refers to the last element.
const numbers = [1, 2, 3, 4, 5];
const result = numbers.slice(-3);
console.log(result);
Output
[3, 4, 5]
Using -3
as the start
index extracts the last three elements of the array.
4. Slicing Beyond Array Bounds
If the start
or end
index is out of bounds, the method handles it gracefully without throwing an error.
const numbers = [1, 2, 3, 4, 5];
const result = numbers.slice(2, 10);
console.log(result);
Output
[3, 4, 5]
The method extracts elements starting from index 2
to the end of the array because the end
index exceeds the array length.
5. Cloning an Array Using slice()
By calling slice()
without any arguments, you can create a shallow copy of an array.
const numbers = [1, 2, 3, 4, 5];
const clonedArray = numbers.slice();
console.log(clonedArray);
Output
[1, 2, 3, 4, 5]
The original array remains unchanged, and a new array with identical elements is created.