Spread
Spread syntax
allows an iterable to expand in place where arguments are expected.
Insert Arrays
let mid = ['peach', 'grape'];
let fruits = ['apple', 'orange', ...mid, 'banana', 'pear'];
console.log(fruits); //expected output: ['apple', 'orange', 'peach', 'grape', 'banana', 'pear']
Slice
let fruits = ['apple', 'grape', 'orange', 'pear'];
let copyFruits = [...fruits];
copyFruits.push('peach');
console.log(fruits); //expected output: ['apple', 'grape', 'orange', 'pear']
console.log(copyFruits); //expected output: ['apple', 'grape', 'orange', 'pear', peach]
Concat
let fruits1 = ['apple', 'grape', 'orange', 'pear'];
let fruits2 = ['peach', 'banana', 'nectarines', 'mangoes'];
let fruitMix = [...fruits1, ...fruits2];
console.log(fruitMix); //expected output: ['apple', 'grape', 'orange', 'pear', 'peach', 'banana', 'nectarines', 'mangoes']
Object.assign
let fruit = {
name: 'apple',
number: 3,
color: 'red'
}
let fruitCopy = {...fruit};
fruitCopy.size = 'small';
console.log(fruitCopy); //expected output: {name: "apple", number: 3, color: "red", size: "small"}
console.log(fruit); //expected output: {name: "apple", number: 3, color: "red"}
Math
let nums = [1, 3, 24, 7, 0, 23];
let max = Math.max(...nums);
console.log(max); //expected output: 24
String to Array
let string = 'Hello World!';
console.log([...string]); //expected output: ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d", "!"]
Loop through HTML Collection
let listItems = document.getElementsByTagName('li');
[...listItems].forEach(item=>console.log(item));
Function arguments
let fruits = ['banana', 'kiwi', 'peach']
const getFavoriteMix = (fruit1, fruit2, fruit3) => {
console.log(`My favorite fruit salad consists of: ${fruit1}, ${fruit2} and ${fruit3}.`); //expected output: My favorite fruit salad consists of: banana, kiwi and peach.
}
getFavoriteMix(...fruits);
MDN: Spread syntax
Codeburst: JavaScript & The spread operator