In this article, you’ll learn what slice function does, how to use it in different scenarios, and some of its properties as well as methods. Let’s get started.
Once the function execution comes to an end, this function returns a completely new array without making any alterations to the original array.
- Start (optional). The first parameter is the start parameter. This is the starting index of an array from which items will be copied.
- End (optional). The second parameter is the end of the index of the array.
- Return value. This method returns a new array containing the selected elements.
As discussed above, slice() function takes two optional parameters. Let’s explore different examples on using these optional parameters.
Syntax Without Parameters
The first parameter is optional and has 0 as a default value, which means if this parameter is not specified the array items will start copying from the beginning of the array.
The second parameter is the end of array index, up to which items will be copied. Note that the item present at this index value will not be copied to the returning array.
Like the first parameter, this is also optional and has default value as length of array on which slice method is applied. All the items up to the last index will be copied.
According to the example above, array1.slice() is equivalent to array1.slice(0,5). That concludes, slice() function without parameters copies all the array items from starting to the end into a new array.
Syntax with Parameters
The slice() function has begin parameter 0 and end parameter 2, this means it returns 2 items starting from index 0 of array.
In this example, the slice function takes parameters 1 and 4. It will slice an array starting from the second item to the fourth item.
If the end parameter is greater than the length of the array, the slice will return an array with items equal to the length of the array.
In this case, the slice function has only a start parameter. The end parameter will default to the length of the array. This is similar to what we had in the previous example where the end parameter is greater than the length of the array.
If we are using negative index values as parameters, the function will indicate the offset from the end of the array. The function will then return the last two elements from the array.
Set up an example and start practicing. Soon, you’ll be able to use the array slice method in your code.