Javascript Array slice() Method with Examples

In this article, we will discuss splice() method for JavaScript array.

Javascript array slice():

  • Extracts a section of an array and returns a new array.
  • It extracts the elements from a specified starting index to end index but excludes the element which is at the end Index.
slice() doesn’t change the original array. It copies a given part of an array and returns that copied part as a new array.

Syntax:

array.slice(startIndex, endIndex);

  • In slice() both parameters are optional.

Example 1:

var colors = ["White", "Yellow", "Orange", "Pink"];

// It will start extraction from an index 2
var slicedColors = colors.slice(2);

console.log(slicedColors);
//output: ["Orange", "Pink"]

console.log(colors);
// output: ["White", "Yellow", "Orange", "Pink"]

Example 2:

In this example, slice() will start extraction from an index 2 and ends at index 4 but exclude the element which is at endIndex (here at index 4).

var colors = ["White", "Yellow", "Orange", "Pink", "Red"];

var slicedColors = colors.slice(2, 4);

console.log(slicedColors);
//output: ["Orange", "Pink"]

console.log(colors);
// output: ["White", "Yellow", "Orange", "Pink"]

Clone an array using slice() method :

As both parameters are optional, without any parameters slice() will start extraction from an index 0. So, we can use it to clone an array.

var originalNumbers = [1, 2, 3, 4, 5];
var clonedNumbers = originalNumbers.slice();

console.log(originalNumbers);
//output: [1, 2, 3, 4, 5]

console.log(clonedNumbers);
//output: [1, 2, 3, 4, 5]

Leave a Reply

avatar
  Subscribe  
Notify of