JavaScript array slice() method
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.
Where:
- start (optional): an integer indicates which index to start selecting elements (the first element has index 0). Negative values are allowed, in this case the index from which the elements will be chosen is calculated using the following formula: array length + start. 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. Negative values are allowed, in which case the index from which elements will be selected is calculated using the following formula: array length + end. No elements are copied if "end" is less than "start"
JavaScript Array Slice Examples
Below are some examples of slicing an array in JavaScript:
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 slice an array from an index to end of the array:
Slicing a specific part of array elements
In this example, the array.slice() method slices certain elements from a given array:
How to slice an array with negative start and end parameters?
An example of calling the array.slice() method to slice an array with a negative parameters: