rest parameter

In JavaScript, the rest parameter syntax allows a function to accept an indefinite number of arguments as an array. It’s useful when you want to handle multiple arguments without explicitly listing them. Three dots denote the rest parameter (...) followed by a parameter name.

Key points:

1. The rest parameter must be the last parameter in the function definition.

2. It collects all remaining arguments passed to the function into an array.

example:


function printValue(a, b, ...others) {
    console.log(a);       // First argument
    console.log(b);       // Second argument
    console.log(others);  // Rest of the arguments as an array
}

printValue(1, 2, 3, 4, 5, 6);
// Output:
// 1
// 2
// [3, 4, 5, 6]

Restrictions:

1. A function can only have one rest parameter.

2. It must be the last parameter in the function’s parameter list.

Example: Handling multiple arguments

You can use the rest parameter to accept a variable number of arguments and perform operations on them.


function multiplyNumber(multiplier, ...numbers) {
    return numbers.map(num => num * multiplier);
}
console.log(multiplyNumber(5, 1, 2, 3, 4, 5)); // Output: [5, 10, 15, 20, 25]

In this example, the multiplyNumber function takes a multiplier as the first argument and multiplies the rest of the arguments by this multiplier.