JavaScript slice array method with 2 examples

The slice method of JavaScript arrays

The slice method is used in arrays to get selected elements of an existing array.  You may specify where to start and end, to select array elements. The index starts at zero. The slice method returns an array that contains those selected elements.

See an example of slice method

Syntax of javascript array slice

Following is the syntax of javascript array slice method:

array_name.slice( starting_index, end_index);

If you do not specify any index number and leave it blank, the whole array will be returned. You can also specify a negative index number in JS slice method.

The index starts at zero.

Also note, that unlike many other Javascript array methods the actual array remains unchanged after using the slice method.

See examples below to learn more about array slice in javascript.

Javascript slice example with start and end index

The following example shows how to use javascript array slice with start and end index numbers. We created a six elements array and printed in HTML paragraph. After that, we used array slice method on that array and assigned the returned array to another array. The returned array’s elements are shown in an alert message. See demo by clicking the link below:

Experience this example online


You see, a new array contains three elements (4,5,6) that are shown in an alert. While array after using javascript slice method is also shown, that remains unchanged.

Javascript array slice example without start and end index

Now look at what happens, if you do not provide start and end index numbers in array slice method. See demo by clicking the link below:

Experience this example online


You can see, the alert showing all elements from the sliced array. The returned array, as mentioned earlier will start slicing array from 0  if you do not specify the starting index number in slice method.

Also see Javascript Array | Javascript splice

Was this article helpful?

Related Articles

Leave A Comment?