The Spread Operator in JavaScript
You can use the "spread" operator in JavaScript to join together different arrays of values. The "spread" operator looks similar to the JavaScript "rest" parameter, but they are completely different concepts. Here are three arrays of strings:
const lunchMenu = ['Greek Salad', 'Open Sandwich', 'Parsnip Soup', 'Flatbread and Dip'] const dinnerMenu = ['Lasagne', 'Strogonoff', 'Tagine', 'Katsu Curry'] const sweetMenu = ['Mixed Berry Ice Cream', 'Chocolate Brownie', 'Orange Cheesecake']
If you print these arrays to the console, you get an array (of course):
console.log(lunchMenu) // ["Greek Salad", "Open Sandwich", "Parsnip Soup", "Flatbread and Dip"]
But if you use the "spread" operator (3 dots) in front of the array name, it separates out the array elements and prints them as separate strings:
console.log(...lunchMenu) // "Greek Salad","Open Sandwich","Parsnip Soup","Flatbread and Dip"
You can use the "spread" operator to make copies of arrays:
const arrayOne = [...arrayTwo]
This "spreads" out the array elements in arrayOne into separate items, then encapsulates them all in a new array named ArrayTwo. You can use the "spread" operator to merge multiple arrays together into one larger array:
const eventMenu = [...lunchMenu, ...dinnerMenu, ...sweetMenu] Console ›['Greek Salad', 'Open Sandwich', 'Parsnip Soup', 'Flatbread and Dip', 'Lasagne', 'Strogonoff', 'Tagine',
'Katsu Curry', 'Mixed Berry Ice Cream', 'Chocolate Brownie', 'Orange Cheesecake']
We've used the "spread" operator to expand these 3 arrays out into their contained values, and store those values in a new array.