- The Rest Operators
...
- The Spread Operators
- [Exercise] Many, Many Arguments
- [Exercise] Spreadin' Arrays
- [Exercise] Mixing Rest and Spread
The rest operator ...
is used to gathering together variables. It can be used in function arguments whenever we want to capture a list of variables or a list of arguments.
function addNumbers(...numbers) {
return numbers.reduce((sum, number) => sum + number, 0);
}
addNumbers([1, 2, 3, 4, 5]);
The spread operator ...
is used to flattening or spreading gathering variables.
const defaultColors = ['red', 'green'];
const userFavoriteColors = ['orange', 'yellow'];
// use concat() method
// ['red', 'green', 'orange', 'yellow']
colors = defaultColors.concat(userFavoriteColors);
// use spread operators
colors = [...defaultColors, ...userFavoriteColors];
We can also mix and match the spread and rest operators.
function validShoppingList(...items) {
if (item.indexOf('milk') < 0) {
return ['milk', ...items];
}
return items;
}
validShoppingList('oranges', 'bread', 'eggs');
Imaging that we're going to update the legacy API in a JavaScript library. We can also use rest and spread operators to catch the balance.
const MathLibrary = {
calculateProduct(...rest) {
console.log('Please use the multiply method instead');
return .this.multiply(...rest);
},
multiply(a, b) {
return a * b;
}
}
Refactor the following function to use the rest operator. Remember, an argument using the rest operator does not need to be called 'rest'
.
function product(a, b, c, d, e) {
var numbers = [a, b, c, d, e];
return numbers.reduce(function(acc, number) {
return acc * number;
}, 1)
}
function product(...numbers) {
return numbers.reduce(function(acc, number) {
return acc * number;
}, 1)
}
Refactor the following to use the spread operator.
function join(array1, array2) {
return array1.concat(array2);
}
function join(array1, array2) {
return [...array1, ...array2];
}
Refactor the following to use only the rest operator.
function unshift(array, a, b, c, d, e) {
return [a, b, c, d, e].concat(array);
}
function unshift(array, ...rest) {
return [...rest, ...array];
}