array.slice() explained with examples#
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
This is its syntax:
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
var animals = ['dog', 'cat', 'monkey', 'donkey', 'dino', 'elephant']; var items;
When no parameters are passed, or zero is passed as the start index:
- It returns a shallow copy of the array.
When only a positive start index in passed:
- It returns the contents of the array starting from the specified index.
When a negative start index in passed:
- 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):
- 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):
- 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:
- It always returns an empty array.
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:
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,
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() works from the examples, it's now upto you to how to use it.
- MDN - Array.slice()