JavaScript slice() Method Array.slice() method

This tutorial introduces the slice() method from the JavaScript Array object. The slice() method returns a "sub-array" of an existing array: numerical arguments passed to determine from which (and, optionally, to which) element to slice. The slice() method is to arrays what substring() is to strings.

This tutorial explains the Array slice() method. Are you looking for the String slice() method?

Related array method:
The splice() method deletes an array subset, and optionally interpolates new elements (values).

Using the slice() Method with One Argument

The script below uses the slice() method to extract a sub-array from the current array, starting at element 2 (the third array element).

var arlene = new Array("alpha","beta","gamma","delta","epsilon");

// Use slice() to return sub-array starting at arlene[2]
alert( arlene.slice(2) +"\n"+ arlene );

The alert in the last line of JavaScript code shows us the the slice() method's return value (an array), and shows us the initial array, as it stands after the operation: the initial array was not modified in any way. JavaScript slice() method

It is also possible to put a limit to the last element to extract, by passing two arguments to the slice() method.

Using the slice() Method with Two Arguments

The script below uses the slice() method to extract a sub-array from the current array, starting at element 2 (the third array element).

var arlene = new Array("alpha","gamma","delta","epsilon","beta");

// Use the slice() method to return the three middle elements
alert( arlene.slice(1,4) +"\n"+ arlene.toString() );

The slice() method in this script extracts a sub-array formed from elements 1, 2, and 3 of the original array. The second argument specifies before which element index to stop; the original array is not modified by slice().

The results returned by our script: JavaScript slice() method with 2 arguments

Using the slice() method with two arguments:

The first argument is inclusive (the array element at this index will be included), but the second defines the index before which, rather than at which, to stop.

Test the slice() Method

Interactively test the slice() method by editing the JavaScript code below and clicking the Test slice() Method button.

Browser support for JavaScript slice() method
Internet Explorer supports the JavaScript slice() methodFirefox supports the JavaScript slice() methodSafari supports the JavaScript slice() methodOpera supports the JavaScript slice() method