Array Slicing

Array slicing allows you to extract a portion of the array.

It takes two parameters: the starting index and the ending index (optional). It returns a new array containing the extracted portion.

Let's perform such operations on the array ['cat', 'dog', 'fish', 'turtle', 'parrot']. Its structure is the following:

array-slicing-structure

Single argument slicing

Positive argument slicing

Output:

In this example, arr.slice(2) skips the first 2 elements of the array - cat and dog.

The remaining part of the array (starting from the 3rd element) is extracted - ['fish', 'turtle', 'parrot'].

Negative argument slicing

Negative indexes count the array elements in reverse.

positive-and-negative-argument-slicing

Output:

In this example, arr.slice(-3) extracts only the last 3 elements of the array - 'fish', 'turtle', and 'parrot'.

Two arguments slicing

Positive arguments slicing

Output:

In this example, arr.slice(1, 3) skips the first element of the array - cat.

Afterwards, it takes the rest of the array until it reaches the 3rd element - dog and fish.

Negative arguments slicing

Output:

In this example, arr.slice(-4, -2) starts slicing at the 4th element counting backwards and ends before the 2nd element counting backwards.

Mixed arguments slicing

Both positive and negative arguments can be specified.

Output:

In this example, arr.slice(1, -1) starts after the first element and ends before the last element.

Invalid cases

An invalid case simply returns an empty array. In such cases, the slicing start argument position is after the slicing end.

Example of valid and invalid cases:

Output:

Another invalid slicing case is specifying a starting argument that's beyond the array's bounds:

Output: