JavaScript’s slice() function returns a shallow duplicate of the array’s chosen area. It does not change the original array; it simply stores the copied piece in a new array.
Syntax
array.slice(start, end)
Parameters
The following parameters are passed to the slice() method:
- start (optional): The array’s duplicated copy’s initial index.
- If nothing is given, it begins at index 0.
- If the value is negative, the offset from the sequence’s end is indicated. Slice(-2) removes the final two items of the sequence, for instance.
- An empty array is returned if start exceeds the sequence’s index range.
- end (optional): The array’s final index after being copied. This list is not exhaustive.
- It extracts to the end of the sequence if nothing is provided.
- Negative results result in extraction up to the end of the sequence. For instance, slice(1,-1) pulls the
- first element from the sequence via the next-to-last member.
- Slice extracts all the way to the sequence’s end if end is longer than the length of the sequence.
Return value
The duplicated values are contained in a new array that the function returns.
const countries = ['USA', 'NIGERIA', 'GHANA', 'GERMANY', 'CHINA'];
console.log(countries.slice(0));
// expected output: Array ['USA', 'NIGERIA', 'GHANA', 'GERMANY', 'CHINA']
console.log(countries.slice(1, 4));
// expected output: Array ['NIGERIA','GHANA', 'GERMANY']
console.log(countries.slice(2, 4));
// expected output: Array ['GHANA', 'GERMANY']
console.log(countries.slice(-3));
// expected output: Array ['GHANA', 'GERMANY', 'CHINA]
console.log(countries.slice(1, -1));
// expected output: Array ['NIGERIA', 'GHANA', 'GERMANY']
Explanation
There are five instances in the code above, each employing a unique strategy. We can see that by using the slice() method on an array and publishing its value, a new array that satisfies the criteria we set is produced.