Execute Program

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 .slice lets 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, -2 means "give me the last two elements".

  • >
    [10, 20, 30, 40, 50].slice(-2);
    Result:
    [40, 50]Pass Icon
  • >
    [10, 20].slice(-2);
    Result:
    [10, 20]Pass Icon
  • 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:
    []Pass Icon
  • 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]Pass Icon
  • Both start and end can be negative. Remember that the end element isn't included in the slice.

  • >
    [10, 20, 30].slice(-3, -1);
    Result:
  • >
    [10, 20, 30, 40, 50].slice(-3, -1);
    Result:
    [30, 40]Pass Icon
  • We can mix positive and negative start and end indexes.

  • >
    [10, 20, 30, 40, 50].slice(1, -1);
    Result:
    [20, 30, 40]Pass Icon
  • >
    [10, 20, 30, 40, 50].slice(-3, 4);
    Result:
    [30, 40]Pass Icon