JavaScript Array slice() Tutorial

In this section, we will learn what the slice() method is and how we can use it in JavaScript.

JavaScript Arrays slice() Method

If we want to extract part of an array object and return it as a new array, we can use the `slice()` method.

This method is basically an easy way of getting a range of an array.

Array slice() Syntax:

array.slice(start, end)

Array slice() Method Parameters:

The `slice()` method takes 2 arguments:

  • The first argument is the start position (index number) from which the extraction should begin.

Notes:

If the first argument is negative, the execution engine will add the length of the array to the negative number and use the result as the value of the first argument.

  • The second argument declares the position (index number) where the extraction should stop.

Notes:

This value is optional and, if ignored, the extraction will start from the start position and end at the last element of the array.

This value is excluded. This means if we set the value 5 for example, the extraction will be up to the index number 4 and not 5.

Just like the first argument, if the second argument is negative, the engine will add the length of the array to the negative value and use the result as the value of the second argument.

Now, if the result is less than the first argument, an empty array object will return as the final result.

For example: slice(5,1) will return an empty array.

Array slice() Method Return Value:

The return value of this method is a new array object that contains the extracted elements.

Example: JavaScript Array Range

const arr = ["Amazon","Apple","Tesla", "Google", "Facebook"];

const newArray = arr.slice(2, arr.length);

console.log(newArray);

Output:

["Tesla", "Google", "Facebook"]
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies