The slice Method for JavaScript Arrays

The slice method copies a section of an existing array into a new array. It does not modify the array it is invoked on. Contrast this with the similarly named splice method which can be used to add, remove, and replace items in an array and which does modify the array it is invoked on.

The slice method returns a new array populated with a contiguous subset of the elements of the array it is invoked on. It supports two arguments: integers that specify starting and ending index locations for the elements to be copied to the new array. The following demonstrates:

var ar = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var ar2 = ar.slice(0, 3);
console.log(ar2); // [ "a", "b", "c" ]

Notice that the resulting array consists of the elements specified by the start location up to but not including that specified by the end location.

Details on start and end arguments

The start and end arguments are optional. If the end argument is omitted, the resulting array consists of the elements from the start location through the end of the array:

var ar = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var ar2 = ar.slice(4); 
console.log(ar2); // [ "e", "f", "g" ]

If no argument or a 0 is passed to the slice method, the entire array is copied:

var ar = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var ar2 = ar.slice(0); 
console.log(ar2); // [ "a", "b", "c", "d", "e", "f", "g" ]

Negative start and/or end arguments

Both the start and end arguments can be specified using negative integers, in which case they specify an offset from the end of the array. The following examples demonstrate negative start and/or end values:

var ar = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
// slice starting 3rd element from end
var ar2 = ar.slice(-3); // [ "e", "f", "g" ]
// slice from 5th element up to but not including last element
var ar3 = ar.slice(4, -1); // [ "e", "f" ]
// slice 4th element from end up to but not including last element
var ar4 = ar.slice(-4, -1); // [ "d", "e", "f" ]

Primitive Values Versus Objects in Arrays

If your arrays consist only of primitive values, just the values are copied by splice. That means that if you make changes to elements in the copy, the original array will remain unchanged.

However, if your arrays consists of elements that are arrays or objects, they are copied by reference. That means if a change is made to a sub-array element or object property in the copied array, it will also be reflected in the original.

For more information see JavaScript Arrays: Value vs Reference.