function sum(...numbers) {
return numbers.reduce((accumulator, current) => {
return accumulator += current;
});
};
sum(1,2) // 3
sum(1,2,3,4,5) // 15
// A perfect example to illustrate this would be if we have a list of numbers,
// and we want to use the first number as the multiplier.
// We then want to put the multiplied value of the remaining numbers in an array:
const multiplyArgs = (multiplier, ...otherArgs) => {
return otherArgs.map((number) => {
return number * multiplier;
});
};
let multipiedArray = multiplyArgs(6, 5, 7, 9);
console.log(multipiedArray); // [30,42,54]
// Here is a good representation of the rest operator and what its value looks like:
const multiplyArgs = (multiplier, ...otherArgs) => {
console.log(multiplier); // 6
console.log(otherArgs); // [5,7,9]
};
multiplyArgs(6, 5, 7, 9);
// Note: The Rest parameter must be the last formal parameter.
const multiplyArgs = (multiplier, ...otherArgs, lastNumber) => {
console.log(lastNumber); // Uncaught SyntaxError: Rest parameter must be last formal parameter
};
multiplyArgs(6, 5, 7, 9);
function multiply(multiplier, ...theArgs) {
return theArgs.map(element => {
return multiplier * element
})
}
let arr = multiply(2, 1, 2, 3)
console.log(arr) // [2, 4, 6]
function restOp(firstNum, ...args) {
let result = [];
for (let i in args) {
const multi = firstNum * args[i];
result.push(multi)
}
return result;
}
console.log(restOp(3, 2, 3, 5));
//Output:[ 6, 9, 15 ]