What is Slice method? What are its uses?

The JavaScript Array slice() method returns a shallow copy of a portion of an array into a new array object.

The slice() method returns a shallow copy of a portion of an array into a new array object selected and end represent from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

Syntax:

Now let’s see all the uses of Slice Array Method.


First use: Simple Copy

Slice without any arguments performs a simple shallow copy.

Second Use: Substring starting at N

The simplest way to use the click method is simple to grab all elements of an array starting at N. Example: It will return all elements from index 1

Third Use: Last N of an array

Slice method can be used is to grab the end of an array, taking advantage of the fact that negative indexed count back from the end. If you want to grab the last 2 digits

Fourth use: first N of an array

Slice method can be used to grab the first element of an array, where we need to use the second argument of the method: end . Example: If you want to grab the first 3 digits.

Fifth use: inner elements of N, starting at m

The above method will not work to get the inner part of the array. For that, we need to convert the slice method (start, end) to (start, length). With a simple function. Example: To get elements starting from 2 and ending at 5:

Sixth use: Handle arbitrary number arguments

Sometimes you want to allow for an arbitrary number of arguments to a function. Example: If you want to create a Math sum function that returns the addition of all arguments


Thank You for Reading ! Stay tuned for Upcoming posts😍