I am Hack Sparrow
Captain of the Internets.

JavaScript slice() with Examples

JavaScript array slice()

Are you familiar with the JavaScript array slice() method? As you are on this page, I will assume you are not. The slice() method of arrays is a useful function to 'chop off' items from an array. 'Chopping off' better describes the functionality than 'slicing', but probably they settled on slice() because it sound and looks more 'professional' than chopoff().

Array.slice() is a method of all instances of arrays in JavaScript, and it accepts two parameters - start index and end index - both of which are optional; and it returns an array of the sliced items. Talking too much technicality will only confuse you, so take a look at these examples and see if you understand anything.

We will base our examples on a variable named animals:

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

Example 1 - when no parameters are passed or only a positive start index in passed

// ["dog", "cat", "monkey", "donkey", "dino", "elephant"]
// ["dog", "cat", "monkey", "donkey", "dino", "elephant"]
// ["cat", "monkey", "donkey", "dino", "elephant"]

Example 2 - when a negative start index in passed

//["dino", "elephant"]
//["dog", "cat", "monkey", "donkey", "dino", "elephant"]

Example 3 - when both the start and end indexes are passed (both positive)

animals.slice(0, 1)
animals.slice(0, 2)
//["dog", "cat"]
animals.slice(2, 2)
animals.slice(2, 3)
animals.slice(2, 5)
//["monkey", "donkey", "dino"]

Example 4 - when both the start and end indexes are passed (end index negative)

animals.slice(1, -1)
//["cat", "monkey", "donkey", "dino"]
animals.slice(1, -2)
//["cat", "monkey", "donkey"]

Example 4 - when an end index is passed with a negative start index

animals.slice(-1, 0)
animals.slice(-1, -2)
animals.slice(-1, 1)

It may appear like slice() can be used to create copies of items in an array, but is unreliable. Take a look at this example:

var people = [{name:'John', age:32}, {name:'Peter', age:154}];
var clone = people.slice(1);
>> [Object { name="Peter", age=154}]
clone[0].age = 10;
>> [Object { name="John", age=32}, Object { name="Peter", age=10}]

Changing clone[0] 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), you get true copies of them in the sliced out 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 slice() works from the examples, it's now upto you to how to use it.

Any questions, queries? Ping me in the comments.

Make a Comment