JavaScript array.slice() explained with examples#

.slice() is a method on all instances of arrays in JavaScript. It accepts two parameters - start index and end index - both of which are optional, and returns an array of the sliced items.

It is a useful function for 'chopping off' items from an array. "Chopping off" better describes the functionality than "slicing", but probably they settled on slice() because it sound better and looks more "professional" than chopoff().

This is its syntax:

array.slice([begin[, end]])

Let's take a look at some examples to better understand how the array.slice() method works. We will base our examples on an array named animals:

var animals = ['dog', 'cat', 'monkey', 'donkey', 'dino', 'elephant'];
var items;

When no parameters are passed, or zero is passed as the start index:

Run
Clear
  • It returns a shallow copy of the array.

When only a positive start index in passed:

Run
Clear
  • It returns the contents of the array starting from the specified index.

When a negative start index in passed:

Run
Clear
  • It returns the contents of the array starting from the last item. The start index now works like a parameter for the number of items to return.

When both the start and end indexes are passed (both positive):

Run
Clear
  • It returns the items from the start index till the end index, the end index item not being included.

When both the start and end indexes are passed (end index negative):

Run
Clear
  • It returns all the items starting from the start index; exclusive of the number of items specified in the end index, in reverse.

When an end index is passed with a negative start index:

Run
Clear
  • It always returns an empty array.

It may appear like Array.slice() can be used to copy an array in whole or in part, but is it is a dangerous assumption. Take a look at this example:

Run
Clear

Changing clone changed people[1] too.

slice() does not create copies of Objects, but references to them, so be careful with the sliced out arrays. However, if the array items are primitive data types (boolean, number, string, null, undefined, NaN), you get true copies of them in the sliced out array.

Array.slice() is very commonly used for getting the first three items or last five items in an array etc. If someone is reversing an array and looping to get the first two items, it can optimized by doing a slice(-2).

You have seen how JavaScript array's slice() works from the examples, it's now upto you to how to use it.

References#

  1. MDN - Array.slice()
Tweet this | Share on LinkedIn |