DEV Community

Cover image for Return a Portion of an Array with .slice()
Todd Carlson
Todd Carlson

Posted on

Return a Portion of an Array with .slice()

This week I am going to explain the .slice() JavaScript array method. Not to be confused with the .splice() method, .slice() allows you to return a portion, or slice as the name implies, of an array. The .slice() method can take in two arguments. The first argument gives the index of where to begin the slice, while the second is the index for where to end the slice (and is non-inclusive). If no arguments are provided the .slice() method starts at the beginning of the array and continues through to the end, basically making a copy of the entire array. I have seen people use .slice() to make copies of arrays, but if making a copy on an array is what I need to do I prefer to use ... which is the spread operator. Also, .slice() is a non-destructive array method, which means that it does not alter the original array.

Here is an example of .slice() in action:

const arr = ["Lindsay", "Tobias", "Gob", "George Michael"];
let newArray = arr.slice(1, 3);
// Sets newArray to ["Tobias", "Gob"]
Enter fullscreen mode Exit fullscreen mode

In this instance, arr.slice(1, 3) starts at the index in the 1 position, and stops at the index in the 3 position returning a new array with the elements at the 1 and 2 indexes while leaving the original array untouched.

Discussion (0)