Rest and Spread Operators Flashcards
What is the rest operator?
It can take multiple arguments and place them into an array. For example, say we have 7 numbered arguments and want to place them into our function as arguments… you can use dot dot dot . Great for unknown number of arguments and capture them into a single array.
function addNumbers(...numbers){ // my argument list may have an unknown number of arguments return numbers.reduce((sum, number) =\> { return sum + number; }, 0); }
addNumbers(1,2,3,4,5,6,7);
What is the spread operator? Why would we use instead of concat?
While the rest operator gathers, the spread operator..spreads. With this operator we created first a new array then inside of it, we referenced existing array and FLATTEN them out.
We can see what exactly is going on with this line of code. And also add some additional elements into the new array!!!!
const defaultColors = ['red', 'green']; const userFavoriteColors = ['orange', 'yellow']; const fallColors = ['fire red', 'fall orange'];
// defaultColors.concat(userFavoriteColors);
[‘green’, ‘blue’, …fallColors, …defaultColors, …userFavoriteColors];
How could you mix and match spread and rest operators?
Say you have a shopping list and you want to validate with inputting items. You ALWAYS need to have milk, so you can use the rest to gather your items list, and then spread to do the validation
function validateShoppingList(…items){
if(items.indexOf(‘milk’) < 0){
return [‘milk’, …items];
}
return items;
}
validateShoppingList(‘oranges’, ‘bread’, ‘eggs’);