What is the Slice Method?
The slice method does not modify the original array or string. Instead, it returns a new array or string that contains the extracted portion.
Practical Example of Slice Method
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].
Using Negative Values with Slice
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].
Using Slice to Copy an Array
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!
Connect me on Twitter,LinkedIn, and GitHub!
Visit my DEV for more articles like this.
Top comments (2)
Great explanation! One thing to note is that
slicewill shallow-copy the array. Value types, e.g.
numberwill be copied, but watch out for reference types: the reference will be copied, meaning that a change in one changes the other.
The output for this example is
In this example, we can see that a change to an object in the array
balso changes the object from
Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍