Sometimes, we want to pass an unknown number of arguments into JavaScript function.
In this article, we’ll look at how to pass an unknown number of arguments into JavaScript function.
How to pass an unknown number of arguments into JavaScript function?
To pass an unknown number of arguments into JavaScript function, we use the rest operator.
For instance, we write
const printNames = (...names) => {
for (const name of names) {
console.log(name);
}
};
to define the printNames
function that takes an infinite number of arguments.
We use the ...
rest operator to get all the arguments into the names
array.
Then we use a for-of loop to loop through all the names
entries and print out all the entries into the console.
Conclusion
To pass an unknown number of arguments into JavaScript function, we use the rest operator.