Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

How to Use the Rest Operator in JavaScript

// 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);
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #How #Use #Rest #Operator #JavaScript
ADD COMMENT
Topic
Name
4+9 =