To pass an unknown number of arguments into a JavaScript function, we can use the rest syntax to make a function accept an infinite number of arguments.
For instance, we can write:
const printNames = (...names) => {
for (const n of names) {
console.log(n)
}
}
printNames('may', 'alex', 'jane')
We have the printNames
method that takes the names
arguments array.
The 3 dots before names
indicates that names
is an array of arguments.
The 3 dots form the rest syntax.
Since names
is an array, we can loop through it with the for-of loop.
We log all the entries of names
that we passed into printNames
as arguments in the last line.
Therefore, we get:
may
alex
jane
from the console log.