The primary functionality of the slice() method can be understood from the following syntax:
The ARRAY or the STRING is joined with the “slice” with the help of the “dot” operator. While the start and the end parameters specify the index from where the slicing starts and ends. Both of these parameters are optional.
As discussed, the slice method slices the string or an array in a defined range (start and ending indexes). If the start or end positions are not defined, the slice(0) creates a copy of the string/array. Let’s overview its detailed working through examples:
Example 1: Slicing an Array
Here, the following code interprets the usage of the slice() method on the Array:
var arr = [20, 40, 60, 80, 100, 120, 140, 160]; var SlArr = arr.slice(3, 6); console.log(SlArr);
An array is initialized, and the “Slarr” variable stores the sliced value of the array starting from the 3rd index to the 6th index.
The output shows that the input string has been sliced to only three indexes.
Example 2: Slicing a String
The provided example demonstrates the application of the slice() method to slice a string:
Here, the slicing is performed on the string starting from the 10th index till the 26th index.
The output has printed the characters falling between the 4th and the 20th index.
Example 3: Creating a Duplicate String/Array
If the slice() method’s start and end parameters are not defined, it creates a duplicate array. This scenario is demonstrated using the code:
var arr = [2, 4, 6, 8, 10, 12]; var SlArr = arr.slice(); console.log(SlArr);
The output shows that the original array has been printed.
The slice() method is used to get the specific part of the string or an array to perform any operation on that part. By default, it does not manipulate the original array. However, if the user wants to update the original string/array, they can replace the result with the original string.