Open In App

What is Array.prototype.slice() method in JavaScript ?

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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() {
    // Original Array
    let arr = [23, 56, 87, 32, 75, 13];
    // Extracted array
    let new_arr = arr.slice(2, 4);
    console.log(arr);
    console.log(new_arr);
}
func();


Output

[ 23, 56, 87, 32, 75, 13 ]
[ 87, 32 ]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads