android-logo

JavaScript Array slice method



slice() is a function for extracting subsets of an array and adding them to a new array. Both the start and finish arguments are optional.

Syntax


slice(start, end);


  • start - This is a starting position and it is optional. The default index value is 0.
  • end - This is a last position and it is optional. The default index value is last element.

Example


const alphabets = [ 'A', 'B' , 'C', 'D' ];
var newAlphabets = alphabets.slice(1, 3);
console.log(newAlphabets);

Output

[ 'B', 'C' ]


Example with negative values


const alphabets = [ 'A', 'B' , 'C', 'D' ];
var newAlphabets = alphabets.slice(-4, -1);
console.log(newAlphabets);

Output

[ 'A', 'B', 'C' ]