The slice method does not modify the original array or string. Instead, it returns a new array or string that contains the extracted portion.
Let’s say you have an array of numbers:
const numbers = [1, 2, 3, 4, 5];
You can use the slice method to extract a portion of this array:
const slicedNumbers = numbers.slice(1, 4); console.log(slicedNumbers); // Output: [2, 3, 4]
In this example, we’re starting the extraction at index 1 (which is the second element in the array) and ending at index 4 (which is the fifth element in the array, but not including it). The resulting slicedNumbers array contains the values [2, 3, 4].
In addition to using positive values for the start and end indexes, you can also use negative values. When you use a negative value, the index is counted from the end of the array or string.
Let’s take the previous example and modify it slightly:
const numbers = [1, 2, 3, 4, 5]; const slicedNumbers = numbers.slice(-3, -1); console.log(slicedNumbers); // Output: [3, 4]
In this example, we’re starting the extraction at index -3 (which is the third element from the end of the array) and ending at index -1 (which is the first element from the end of the array, but not including it). The resulting slicedNumbers array contains the values [3, 4].
You can also use the slice method to create a copy of an array. This is useful if you want to make changes to the copy without affecting the original array.
Here’s an example:
const originalArray = [1, 2, 3, 4, 5]; const copiedArray = originalArray.slice(); console.log(copiedArray); // Output: [1, 2, 3, 4, 5]
In this example, we’re using the slice method without any parameters, which means we’re extracting the entire array. The resulting copiedArray contains the same values as the originalArray.
Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!
Visit my DEV for more articles like this.