Overview
In this tutorial, you will learn how to utilize JavaScript rest parameters to gather multiple function arguments effectively in an array.
Introduction to Rest Parameters
ES6 brought the rest parameter, represented by three dots (…)
, that enables functions to accept an indefinite number of arguments as an array.
Syntax
const fn = (a, b, ...args) => {
// args is an array
};
Here, a
and b
capture the first two arguments, and args gathers the rest as an array.
Example Usage:
fn(1, 2, 3, "A", "B", "C");
In this case, args stores:
[3, "A", "B", "C"]
If only two arguments are passed:
fn(1, 2);
Then args is an empty array:
[]
Rest Parameter Rules
Must be the last parameter in a function definition:
const fn = (a, ...rest, b) => { // ❌ Syntax Error
};
//SyntaxError: Rest parameter must be last formal parameter
More Examples:
1. Summing Numbers definition
const sum = (...args) => args.reduce((total, a) => total + a, 0);
console.log(sum(1, 2, 3)); // Output: 6
2. Filtering Only Numbers
If arguments contain different data types, filter out only numbers:
const sum = (...args) => args
.filter(e => typeof e === 'number')
.reduce((prev, curr) => prev + curr, 0);
console.log(sum(10, 'Hi', null, undefined, 20)); // Output: 3
Rest Parameters vs Arguments Object
The arguments object is present in legacy functions but is not an actual array. Therefore, it does not include array methods such as filter()
and reduce()
.
Example Without Rest Parameters (Using arguments)
function sum() {
return Array.prototype.filter.call(arguments, e => typeof e === 'number')
.reduce((prev, curr) => prev + curr, 0);
}
Rest parameters make the code more readable and modern.
Filtering Arguments by Type
const filterBy = (type, ...args) => args.filter(e => typeof e === type);
Rest Parameters with Arrow Functions
Arrow functions do not have an arguments
object, so the rest parameters are necessary:
const combine = (...args) => args.join(" ");
console.log(combine("JavaScript", "Rest", "Parameters")); // Output: "JavaScript Rest Parameters"
Rest Parameters in Dynamic Functions
You can use rest parameters in functions created dynamically with the Function
constructor:
const showNumbers = new Function('...numbers', 'console.log(numbers)');
showNumbers(1, 2, 3); // Output: [1, 2, 3]
Conclusion
Rest parameters permit functions to receive any amount of arguments as an array.
They have to be the last parameter of a function.
Unlike arguments, rest parameters are actual arrays and include array methods.
Top comments (0)