Mastering JavaScript's slice()

Hero image for Mastering JavaScript's slice(). Image by Josué AS.
Hero image for 'Mastering JavaScript's slice().' Image by Josué AS.

JavaScript's Array.prototype.slice() method is a versatile tool used to create a shallow copy of a portion of an array without altering the original array. It can be incredibly useful for tasks such as extracting elements, creating subarrays, and performing nondestructive operations on arrays.


What is prototype.slice()?

The slice() method belongs to the Array prototype, which means it is available for use on any instance of an array. It returns a new array containing a copy of a portion of the original array (defined by the arguments you pass into it). The original array remains unmodified.


Syntax of prototype.slice()

The slice() method takes two arguments:

  • start (optional): The zerobased index at which to start extraction. A negative index can be used, indicating an offset from the end of the sequence.
  • end (optional): The zerobased index before which to end extraction. slice extracts up to but not including end. If end is omitted, slice extracts through the end of the sequence (arr.length).

Here's what that looks like:

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

How Does It Work?

When slice() is called on an array, it begins at the specified start index, extracts elements from the array up until the end index, and returns a new array. If the start is undefined, it will default to the start of the array: 0; if the end is undefined, then it will extract through to the end of the array.


A Code Example

Here's a quick example of using slice():

const numbers = [1, 2, 3, 4, 5];const slicedNumbers = numbers.slice(1, 4);console.log(slicedNumbers);  //=> [2, 3, 4]console.log(numbers);  //=> [1, 2, 3, 4, 5] (the original array is untouched)

Here, slice() creates a new array called slicedNumbers containing the elements with indexes 1 to 3 from the numbers array.


Negative Indexes

You can also use negative indices to begin the slice from the end of the array rather than the start:

const slicedNumbers = numbers.slice(-3);console.log(slicedNumbers);  //=> [3, 4, 5]

Here, you can see that slice() has extracted the last three elements from the numbers array.


Cloning an Array

Although not strictly what it is intended for, slice() is also often used to create a shallow copy of an entire array. For example:

const clonedNumbers = numbers.slice();console.log(clonedNumbers);  //=> [1, 2, 3, 4, 5]

Here, since start and end are both omitted, slice() copies all of the elements of numbers.


Using slice() for Strings

While slice() is an Array method, it can also be applied to arraylike objects. For instance, if you pass a string into slice, it will 'convert' it into an array of characters:

const string = 'Hello';const stringArray = string.slice();console.log(stringArray);  //=> ['H', 'e', 'l', 'l', 'o']

This technique leverages the .call() function to "borrow" the slice method from Arrays and apply it to an arraylike object like string.

I should say though that this is a little academic; if you wanted to separate a string into an array of letters, you would almost certainly use split() instead.


Caveats and Considerations

  • slice() does not mutate the original array. It performs a shallow copy, which means that if the array contains objects, the new array will have references to the same objects.
  • If start is greater than the index range of the array, an empty array is returned.

Wrapping up

Array.prototype.slice() is a highly effective JavaScript method for extracting portions of an array, cloning arrays, and working with arraylike objects. Its nondestructive nature allows developers to work with arrays flexibly and efficiently without risking the integrity of the original data structure.


Categories:

  1. Development
  2. Front‑End Development
  3. Guides
  4. JavaScript