JavaScript Array slice() method
The slice()
method in JavaScript is used to extract a portion of an array and return it as a new array without modifying the original array. The method selects elements from the start
index up to, but not including, the end
index.
Syntax:
start
(optional): The index at which to start extracting elements. If omitted, extraction starts from index0
.end
(optional): The index before which to end extraction (not included). If omitted, extraction continues to the end of the array.
Return Value:
- A new array containing the extracted elements.
Key Points:
- Does not modify the original array:
slice()
returns a new array and does not affect the original array. - Start is inclusive and end is exclusive: The element at the
start
index is included in the result, but the element at theend
index is not. - Handles negative indices: Negative indices can be used to count elements from the end of the array.
Example 1: Basic usage
In this example, the slice starts at index 1
and ends at index 4
(exclusive), so it extracts elements at indices 1
, 2
, and 3
.
Example 2: Omitting the end
parameter
If you omit the end
parameter, slice()
extracts all elements starting from the start
index to the end of the array.
Example 3: Using negative indices
Negative indices count from the end of the array:
-3
refers to the third-to-last element (orange
).-1
refers to the last element but is excluded.
Example 4: Copying an entire array
By calling slice()
without any arguments, you can create a shallow copy of the array.
Summary:
slice()
extracts a portion of an array and returns it as a new array without modifying the original array.- The
start
index is inclusive, while theend
index is exclusive. - It handles negative indices, allowing you to extract elements from the end of the array.
- It's commonly used to copy an array or extract specific parts of an array.