JavaScript(JS) array method - slice
The slice()
method in JavaScript is used to extract a section of an array and return a new array containing the selected elements. The original array is not modified.
The slice()
method takes two arguments: the starting index (inclusive) and the ending index (exclusive). If only one argument is provided, slice()
will extract elements from the provided index to the end of the array.
Here's an example of how to use the slice()
method:
let array = ["one", "two", "three", "four", "five"]; let slicedArray = array.slice(1, 4); console.log(slicedArray); // ["two", "three", "four"] console.log(array); // ["one", "two", "three", "four", "five"]Sourcefigi.www:tidea.com
In this example, we have an array array
containing the elements ["one", "two", "three", "four", "five"]
. We use the slice()
method to extract a section of the array starting from index 1 (inclusive) and ending at index 4 (exclusive).
The slice()
method returns a new array containing the selected elements. In this case, slicedArray
is ["two", "three", "four"]
.
The original array
is not modified by the slice()
method. After the slice()
method is executed, the array
is still ["one", "two", "three", "four", "five"]
.
We log the sliced array to the console using console.log(slicedArray)
. We also log the original array
to the console to demonstrate that it has not been modified.