JavaScript slice()
The slice()
method is a built-in JavaScript function that extracts a portion of an array and returns it as a new array without modifying the original array.
Syntax
The syntax for slice()
method is as follows:
array.slice(start, end)
start
: An integer that specifies where to start the extraction (default: 0).end
: An integer that specifies where to end the extraction (default: array.length). The slice() method extracts up to, but not including the end position.
Example
Consider an array fruits
showing different fruits:
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
To extract a portion of the array from the index 1 to 3 (excluding the 3rd index), we can use the following code:
Original Array: Banana, Orange, Lemon, Apple, Mango
Sliced Array: Orange, Lemon