JavaScript Arrays: Slice With Negative Arguments
Welcome to the Slice With Negative Arguments lesson!
JavaScript arrays' "slice" method can take negative index arguments, allowing us to slice from the end of the array.
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We've seen that
.slicelets us get a range of elements from an array. If we pass a negative index to.slice, it means "give me this many elements from the end of the array". For example,-2means "give me the last two elements".>
[10, 20, 30, 40, 50].slice(-2);Result:
[40, 50]
>
[10, 20].slice(-2);Result:
[10, 20]
In an earlier lesson, we saw what happens when we slice past the end of the array with a positive argument. Here's a reminder: in the next example, there's no element at index 4, so we get an empty array.
>
[10, 20].slice(4, 5);Result:
[]
With negative indexes, we can also slice before the beginning of the array. The result will only include elements in the original array. It won't invent additional elements to satisfy our out-of-bounds index.
>
[10, 20].slice(-100);Result:
[10, 20]
Both
startandendcan be negative. Remember that theendelement isn't included in the slice.>
[10, 20, 30].slice(-3, -1);Result:
>
[10, 20, 30, 40, 50].slice(-3, -1);Result:
[30, 40]
We can mix positive and negative
startandendindexes.>
[10, 20, 30, 40, 50].slice(1, -1);Result:
[20, 30, 40]
>
[10, 20, 30, 40, 50].slice(-3, 4);Result:
[30, 40]