techStackGuru

JavaScript Array Slicing


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' ]

Javascript string slicing

const str = "Hello world";
const res = str.slice(0, 5); 

console.log(res); // Hello

A new string is returned from the slice() method by extracting the characters from index 0 to index 4. The original string is not modified by the slice method. The substring method can be used instead if you wish to modify the string.