Skip to content

JavaScript array slice example

Ramesh Fadatare edited this page Aug 11, 2020 · 1 revision

The slice() method returns a shallow copy of an array portion. The method takes one or two parameters, which specify the indexes of the selection. The original array is not modified.

JavaScript array slice example

In the example, we create two slices.

const nums = [2, -3, 4, 6, -1, 9, -7];

const res = nums.slice(3);
console.log(res);

const res2 = nums.slice(2, 4);
console.log(res2);

We create a slice from index 3 until the end of the array:

const res = nums.slice(3);

We create a slice from index 2, to index 4; the ending index is non-inclusive:

const res2 = nums.slice(2, 4);

This is the output:

[ 6, -1, 9, -7 ]
[ 4, 6 ]

Clone this wiki locally