Image of a cloud

Cloud Coding

Slice Method in JS

By: Tristan Pedersen

Slice Method in JS

The slice() method returns a shallow copy of a portion of an array into a new array, so the original array will not be affected.

slice() takes in two arguments; the start and end (the end not included) which are the indexes of items in that array that will go into your shallow copy. Both of these arguments are optional.

The slice() method is sparse, if the slice portion of the array is sparse; the return is sparse as well

Ex.

let data = ["1", "2", "3", "4", "5"];
console.log(data.slice(2));
//output: ["3", "4", "5"];

The slicing of the array starts from index 2 in this scenerio.

Ex.

let data = ["1", "2", "3", "4", "5"];
console.log(data.slice(2, 4));
//output: ["3", "4"];

The slicing of the array starts at index 2 and ends(but does not include) at index 4.

Summary: The slice() method of Array returns a shallow copy of a portion of the original array into an array object. This portion will be selected from start to end (not including the end). The original array will not be changed. slice() is a copy method, it does not alter the orignial but instead will return a shallow copy of the original based on the start and end you give it in the parameters. slice() will preserve empty slots. If the slice portion is sparse; the return will also be sparse.