In the old days, we can use the arguments variable to get the dynamic parameters that are passed to a function.
const sum = function() {
return Array.from(arguments).reduce((a, b) => a + b, 0);
};
sum(1); // 1
sum(1, 2); // 3
sum(1, 2, 3); // 6
sum(1, 2, 3, 4); // 10However, most of us aren't aware about the existence of arguments. It has some drawbacks such as
- It's not an array, so we usually have to convert it to array first in order to use
Arraymethods - More importantly, it isn't available in arrow functions
The ES6 rest parameter (...) provides an easier way to work with an unknown numbers of parameters. The sum function above can be written as following:
const sum = (...params) => params.reduce((a, b) => a + b, 0);
sum(1, 2, 3, 4, 5); // 15More
