The array.slice(start, end) method returns a shallow copy of the array containing a portion of the original array. A shallow copy is an exact copy of the original object's values one level deep. This means that if any fields of an object are referred to other objects, only the addresses will be copied, but not the objects themselves. The array.slice() method does not change the original array. The slice() method copies object references to a new array, with the original and the new array referring to the same object. If the object by reference is changed, then the changes will be visible both in the original and in its copy. Changing a string or number in one array does not affect the other in any way. If a new element is added to the original array or copy, it will not affect the different array.
- start (optional): an integer indicates which index to start selecting elements (the first element has index 0). If the parameter is not specified, then the default value will be zero;
- end (optional): an integer specifying where the selection of array elements ends. If this parameter is not specified, then all elements from the initial position (start) to the end of the array will be selected.
Copying the entire array
In this example, the array.slice() method copies the entire array since no arguments are passed:
Copying from a specific index up to the end of an array
An example of using the array.slice() method to copy an array from an index to the end of the array:
Slicing elements from the middle of an array
In this example, the array.slice() method copies the elements from the middle of the given array:
Slicing elements from the end of an array
In this example, the array.slice() method copies the elements from the end of the given array:
Slicing a specific part of an array elements
In this example, the array.slice() method copies certain elements from a given array:
How to slice an array with negative start and end parameters?
An example of using the array.slice() method to slice an array with negative parameters: