What is Array.prototype.slice() method in JavaScript ?
Last Updated :
01 Feb, 2024
The Array.prototype.slice()
method in JavaScript is used to extract a portion of an array and create a new array containing the selected elements. It does not modify the original array. instead, it returns a shallow copy of a portion of the array.
Syntax:
array.slice(startIndex, endIndex);
Parameters:
startIndex
: The index at which to begin extraction (inclusive).
endIndex
: The index at which to end extraction (exclusive).
Example: Here, the slice() method extracts the array from the given array starting from index 2 and including all the elements less than index 4.
Javascript
function func() {
let arr = [23, 56, 87, 32, 75, 13];
let new_arr = arr.slice(2, 4);
console.log(arr);
console.log(new_arr);
}
func();
|
Output
[ 23, 56, 87, 32, 75, 13 ]
[ 87, 32 ]
Share your thoughts in the comments
Please Login to comment...