How can I get an indefinite number of arguments as an array in a function? First, I will try this way.
const printAll = (args) => {
console.log(args);
};
printAll(1, 3, 5, 7, 10);
I can get only the first argument of the array. That's not what I want ๐
This time, I will use the Rest parameters.
const printAll2 = (...args) => {
console.log(args);
};
printAll2(1, 3, 5, 7, 10);
Now, I can get all arguments as an array. ๐
I will use the forEach, so I can print all the arguments!
const printAll3 = (...args) => {
args.forEach((arg) => {
console.log(arg);
});
};
printAll3(1, 3, 5, 7, 10);
Reference: MDN Rest parameters