The slice() method returns a shallow copy of a portion of an array into a new array object.
Example
slice() Syntax
The syntax of the slice() method is:
arr.slice(start, end)
Here, arr is an array.
slice() Parameters
The slice() method takes in:
- start (optional) - Starting index of the selection. If not provided, the selection starts at start 0.
- end (optional) - Ending index of the selection (exclusive). If not provided, the selection ends at the index of the last element.
slice() Return Value
- Returns a new array containing the extracted elements.
Example 1: JavaScript slice() method
Output
[ 'JavaScript', 'Python', 'C', 'C++', 'Java' ] [ 'C', 'C++', 'Java' ] [ 'Python', 'C', 'C++' ]
Example 2: JavaScript slice() With Negative index
In JavaScript, you can also use negative start and end indices. The index of the last element is -1, the index of the second last element is -2, and so on.
Output
[ 'JavaScript', 'Python', 'C', 'C++' ] [ 'C', 'C++', 'Java' ]
Example 3: JavaScript slice() with Objects as Array Elements
The slice() method shallow copies the elements of the array in the following way:
- It copies object references to the new array. (For example, a nested array) So if the referenced object is modified, the changes are visible in the returned new array.
- It copies the value of strings and numbers to the new array.
Output
{ name: 'David', age: 23 }
{ name: 'Levy', age: 23 }
Recommended Reading: JavaScript Array.splice()