Rest and Spread Operators Flashcards

1
Q

What is the rest operator?

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the spread operator? Why would we use instead of concat?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How could you mix and match spread and rest operators?

A

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’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly