Home » Programming » Javascript » Javascript Slice

Array slice() Method in JavaScript, with Examples

We have covered removing items from arrays in JavaScript, as well as checking whether an item is present in an array.

This article will look at copying or returning a subsection of arrays using the slice() method in Javascript.

slice() Syntax

arr.slice([start[, end]])

Where:

  • arr is an array or existing array variable
  • start is the index to start the slice at
  • If it is undefined, it will default to 0
  • The index is the position of the item within the array. Remember, they start at 0!
  • end is the index to end the slice at
  • If it is undefined, the end of the array will be used
  • A new array will be returned, containing the value of the elements between and including the start and end indexes
  • This is an entirely new array. Modification made to elements in it will not affect the original array

Examples of Array slice() Method in JavaScript

The below example creates a new array containing the animals with wings by extracting them from the animals array by their position:

var animals = ['Cat', 'Dog', 'Parrot', 'Pigeon', 'Flamingo', 'Elephant'];
var wings = animals.slice(2, 4);

// animals contains ['Cat', 'Dog', 'Parrot', 'Pigeon', 'Flamingo', 'Elephant']
// wings contains ['Parrot', 'Pigeon', 'Flamingo']

Using Negative Indexes

Negative indexes can also be supplied to work backward from the last index:

var animals = ['Cat', 'Dog', 'Parrot', 'Pigeon', 'Flamingo', 'Elephant'];
var wings = animals.slice(-4, -1);

// animals contains ['Cat', 'Dog', 'Parrot', 'Pigeon', 'Flamingo', 'Elephant']
// wings contains ['Parrot', 'Pigeon', 'Flamingo']

Conclusion

Getting a portion of an array is particularly useful for things like pagination – when you have a long array of data that you want to break into chunks for display.

Check out our other JavaScript tutorials and explainers!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment