Skip to content
Home » JS: slice() Method

JS: slice() Method

    The<span style="color:#cf2e2e" class="tadv-color"> slice()</span> method is part of JavaScript Array class. It extract certain elements from an array and returns a new array.

    There are different ways to select elements using <span style="color:#cf2e2e" class="tadv-color">slice()</span> in JavaScript.

    The<span style="color:#cf2e2e" class="tadv-color"> slice()</span> method takes two parameters – start index and the end index of an array. It does not include the last element while returning a new array.

    Examples of slice() method

    In these examples, we will extract from an array using different forms of <span style="color:#cf2e2e" class="tadv-color">slice()</span> syntax.

    // declare the array
    myArray = ["one", "two", "three", "four"];
    // only start index is mentioned
    var result1 = myArray.slice(2);
    console.log(result1);

    The <span style="color:#cf2e2e" class="tadv-color">slice() </span>method will start extracting from index 2 and since the end index is not mentioned, it will extract the rest of elements from the array. The result of the above program is given below.

    ["three", "four"]

    In the next example, we will mention both start as well as end index value. Here is the example script.

    // declare the array
    myArray = ["one", "two", "three", "four"];
    // both start index and end index is mentioned
    var result = myArray.slice(1,3);
    console.log(result);

    The array start with index <span style="color:#cf2e2e" class="tadv-color">1 </span>of the array. At index <span style="color:#cf2e2e" class="tadv-color">1</span>, the element is “two” and ends with index 2 because the end value 3 in <span style="color:#cf2e2e" class="tadv-color">slice(1,3)</span> is not included.

    The output is as follows.

    Sometimes you want to extract elements starting from end to start of the array. It is also known as negative index.

    // declare the array
    myArray = ["one", "two", "three", "four"];
    // negative index starts from -1
    var result = myArray.slice(-3,-1);
    document.body.innerHTML = result;

    The negative index starts from <span style="color:#cf2e2e" class="tadv-color">-1</span>. The element at<span style="color:#cf2e2e" class="tadv-color"> -1 </span>position is “<span style="color:#cf2e2e" class="tadv-color">three</span>” in the above example array.

    You cannot use index <span style="color:#cf2e2e" class="tadv-color">0 </span>because it is a positive index and starts from beginning of the array.

    The output of the above code is as follows.

    two,three