The slice() method is used to get some specific elements of an array from a given starting index to the given ending index.
Syntax of slice() method
The slice method takes two arguments as a parameter and provides the sliced array. The syntax of writing a slice() function is given below:
- The slice() method does not affect the original array and returns a new sliced array.
- The last element of the given range of the indices is not included in the resulting array.
Let’s try to slice a couple of arrays to understand the slice() function better.
Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:
- Use the F12 key in Chrome and other chromium-based browsers.
- Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
- Use Option + ⌘ + C keyboard shortcut keys in Safari (if the developer menu does not appear, open Preferences by pressing ⌘ + , and in the Advanced tab, check “Show Develop menu in menu bar”).
Suppose we have an array of different programming languages:
We want to get the name of the languages from the second index to the fifth index. The syntax for getting such a result would go like this:
Now, if we console the slicedArr:
You can see that we have got three elements from the second index to the fifth index.
- The array index starts from zero
- The fifth element, the last element in the range of indices, is not included in the resulting array, as mentioned earlier.
How to slice from the end of the array
We can also extract elements from the end of the array by providing the negative values to the slice function.
Negative zero(-0) will be considered the last element of the array, negative one(-1) will be considered the second last element of the array, and so on.
For example, we have an array of programming languages:
We want to get the elements from the fourth last index to the second last index. The slice() function for getting such a result will go like this:
To verify, console the slicedArr:
We have got the exact result as we expected. So this is how we can use negative values to extract elements from the end of the array.
We learned how to use the slice() method to get a subset of elements from an array in this how-to guide.