When we see "..." in the code, it is either rest parameters or the spread syntax.
function sumAll(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
alert( sumAll(1) ); // 1
alert( sumAll(1, 2) ); // 3
alert( sumAll(1, 2, 3) ); // 6
// (1) Expands array into a list of arguments
alert( Math.max(3, 5, 1) ); // 5
// Not working
let arr = [3, 5, 1];
alert( Math.max(arr) ); // NaN
// Working!
let arr = [3, 5, 1];
alert( Math.max(...arr) ); // 5 (spread turns array into a list of arguments)
// (2) Merge arrays
let arr = [3, 5, 1];
let arr2 = [8, 9, 15];
let merged = [0, ...arr, 2, ...arr2];
// (3) Copy
let arr = [1, 2, 3];
let arrCopy = [...arr];
The spread syntax internally uses iterators to gather elements, the same way as for..of does.
let str = "Hello";
alert( [...str] ); // H,e,l,l,o
alert( Array.from(str) ); // H,e,l,l,o (more universal)