Copying Parts of an Array
slice copies part of an array into a new array. The original array does not change:
const nums = [10, 20, 30, 40, 50];
console.log(nums.slice(1, 3));
console.log(nums.slice(2));
console.log(nums.slice(-2));
console.log(nums);
Output:
[ 20, 30 ]
[ 30, 40, 50 ]
[ 40, 50 ]
[ 10, 20, 30, 40, 50 ]
slice(start, end) begins at index start and stops just before index end. The element at end is not included. So slice(1, 3) gives the elements at index 1 and 2. This rule makes counting easy: slice(1, 3) has 3 - 1 = 2 elements, and slice(0, k) gives exactly the first k elements.
With only one argument, slice goes to the end of the array. A negative number counts from the end, so slice(-2) gives the last two elements. The last line shows that nums is unchanged.
slice also accepts positions outside the array without an error:
console.log(nums.slice(3, 99));
console.log(nums.slice(3, 1));
console.log(nums.slice());
Output:
[ 40, 50 ]
[]
[ 10, 20, 30, 40, 50 ]
An end past the last element simply stops at the end. If start is not before end, you get an empty array. With no arguments at all, slice() copies the whole array.
The spread syntax is three dots, .... Inside square brackets, ...nums puts all the elements of nums into the new array:
console.log([...nums, 60]);
console.log([0, ...nums]);
const left = [1, 2];
const right = [3, 4];
console.log([...left, ...right]);
Output:
[ 10, 20, 30, 40, 50, 60 ]
[ 0, 10, 20, 30, 40, 50 ]
[ 1, 2, 3, 4 ]
[...nums, 60] is a new array: a copy of nums with 60 added at the end. Put a value before the spread to add it at the front. Use two spreads to join two arrays into one.
Spread also works inside a function call. Math.max(...nums) passes each element as a separate argument, as if you had typed Math.max(10, 20, 30, 40, 50):
console.log(Math.max(...nums));
Output:
50
Why leave the original array alone? Other parts of your program may still use it. If you build a new array instead of changing the old one, the old one stays correct. A lot of modern JavaScript code is written in this style, and slice and spread are the main tools for it.
In the exercise, print a slice, the last two elements, a copy with 60 added at the end, and then the original array.