Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Array slice() Method

JavaScript Array slice() Method

The Javascript arr.slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged.

Syntax:

arr.slice(begin, end)

Parameters: This method accepts two parameters as mentioned above and described below:

  • begin: This parameter defines the starting index from where the portion is to be extracted. If this argument is missing then the method takes begin as 0 as it is the default start value.
  • end: This parameter is the index up to which the portion is to be extracted (excluding the end index). If this argument is not defined then the array till the end is extracted as it is the default end value If the end value is greater than the length of the array, then the end value changes to the length of the array.

Return value: This method returns a new array containing some portion of the original array. 

Below is an example of the Array slice() method.

Example 1: In this example, 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]

Example 2: In this example, the slice() method extracts the entire array from the given string and returns it as the answer, Since no arguments were passed to it.

JavaScript




function func() {
    //Original Array
    let arr = [23, 56, 87, 32, 75, 13];
    //Extracted array
    let new_arr = arr.slice();
    console.log(arr);
    console.log(new_arr);
}
func();


Output:

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

Example 2: In this example, the slice() method extracts the array starting from index 2 till the end of the array and returns it as the answer.

JavaScript




function func() {
    //Original Array
    let arr = [23, 56, 87, 32, 75, 13];
    //Extracted array
    let new_arr = arr.slice(2);
    console.log(arr);
    console.log(new_arr);
}
func();


Output:

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

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers: The browsers supported by JavaScript Array from() method are listed below:

  • Google Chrome 45.0
  • Microsoft Edge 12.0
  • Mozilla Firefox 32.0
  • Safari 9.0
  • Opera 25.0

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.

RELATED ARTICLES

Most Popular

Recent Comments