KandZ – Tuts

We like to help…!

JavaScript 23 🧬 rest parameters


a - rest parameters introduction
rest parameters provide a way to handle an indefinite number of arguments as an array.
They were introduced in ES6 (ECMAScript 2015)
They offer a more concise syntax for working with functions that accept a variable number of arguments.
The rest parameter must be the last parameter in a function definition.
Only one rest parameter can be used per function.
It works well with destructuring assignment, allowing you to extract specific elements from the array while collecting the rest
Rest parameters are a powerful feature in JavaScript, making your code cleaner and more maintainable by providing an elegant way to handle multiple arguments.

b - rest parameters use cases and examples
Use Cases:
1 Creating flexible functions that can handle any number of arguments.
2 Simplifying code when dealing with variadic functions (functions with a variable number of parameters).
3 Working with arrays or other iterable objects where you want to separate specific elements from the rest.
syntax:

function functionName(param1, param2, ...restOfParams) {
// ...
}

param1 and param2 are regular parameters.
...restOfParams is the rest parameter, which collects all additional arguments passed
Example 1 → numbers is an array containing all the arguments passed to the function.
Example 2 → greeting is the first argument, and names collects the rest of the arguments into an array.
Example 3 → multiplier is the first argument, and values contains the rest of the arguments.

Leave a Reply