Introduction

The slice() method on arrays returns a shallow copy of the selected elements in a new array object. It uses two parameters start and end to specify the position of the array that we want to slice.

The start parameter determines where to start the selection whereas, end determines the end of the selection. The end index element is not included in the new array selection. Both the parameters are optional.

Examples

let arr = ["One", "Two", "Three", "Four", "Five", "Six"];

let newArr = arr.slice(1, 3); 

console.log(newArr); // ['Two', 'Three']

In the above example, start value specified is 1 so it starts from the second element(since the arrays start from index 0). The element with the start index is included in the new array. This is why newArr will contain the element “Two”. end value is 3 so the element at the index 3 is “Four” but this value is exclusive and hence not included in the newArr. So, the newArr contains elements Two and Three.

Let us look at more examples,

let arr = ['Never', 'trust', 'atoms;', 'they', 'make', 'up', 'everything.'];

let arr2 = arr.slice(0, 4);
console.log(arr2); // ['Never', 'trust', 'atoms;', 'they']

let arr3 = arr.slice(3, 6);
console.log(arr3); // ['they', 'make', 'up']

let arr4 = arr.slice(1, 5);
console.log(arr4); // ['trust', 'atoms;', 'they', 'make']

If you do not pass any parameters, slice() method will return a shallow copy of the array.

let arr = ['Never', 'trust', 'atoms;', 'they', 'make', 'up', 'everything.'];

let arr2 = arr.slice();
console.log(arr2); // ['Never', 'trust', 'atoms;', 'they', 'make', 'up', 'everything.']

The new array arr2 is the shallow copy of array arr.

You can also pass negative numbers to slice() method. The -1 represents the last element of the array, -2 represents the index of the second last element and so on.

let arr = ['Never', 'trust', 'atoms;', 'they', 'make', 'up', 'everything.'];

let arr2 = arr.slice(-1);
console.log(arr2); // ['everything.']

let arr3 = arr.slice(-2);
console.log(arr3); // ['up', 'everything.']

let arr4 = arr.slice(-4, -1);
console.log(arr4); // ['they', 'make', 'up']

slice() method returns a shallow copy

It is important to note that the slice() can be used to lone an array but it will create a shallow copy of the array. This is because array is stored as a reference. So, if you have a complex array structure, you will need to deep clone the array.

let arr = ["One", ["Two", "3"], "Three", "Four", "Five", "Six"];

let newArr = arr.slice(); 

console.log(arr); // ['One', ['Two', '3'], 'Three', 'Four', 'Five', 'Six']
console.log(newArr); // ['One', ['Two', '3'], 'Three', 'Four', 'Five', 'Six']

Now, if we try to push a new element in the newArr’s second element which is an inner array, the changes will reflect in both the arrays.

newArr[1].push('4');
console.log(arr); // ['One', ['Two', '3', '4'], 'Three', 'Four', 'Five', 'Six']
console.log(newArr); // ['One', ['Two', '3', '4'], 'Three', 'Four', 'Five', 'Six']