How to accept unlimited parameters in a JavaScript function
By Flavio Copes
Learn how to write a JavaScript function that accepts an unlimited number of arguments, using rest parameters that collect them into a single array.
To accept unlimited parameters in a JavaScript function, use a rest parameter: three dots before the parameter name. All the arguments get collected into a single array.
Let me show you the problem this solves.
Let’s say we have a function called join() whose job is to join all the strings we pass to it.
For example we write a prototype that accepts 2 strings:
const join = (string1, string2) => {
return string1 + string2
}
and when we call it, we get a string that is the concatenation of the 2 arguments we pass:
join('hi', ' flavio') // 'hi flavio'
One way is to append additional parameters that default to an empty string, like this:
const join = (string1, string2, string3 = '') => {
return string1 + string2 + string3
}
but this approach does not scale well, because we’d need to add a large number of parameters and our code would look pretty bad. What if someone passes 20 strings?
Enter rest parameters
Instead, we can use the ... syntax followed by the name of the parameter:
const join = (...strings) => {
return strings.join('')
}
Inside the function, strings is a real array. That’s why we can call its .join() method to concatenate the strings it contains, passing an empty string as argument (otherwise it defaults to concatenating strings adding a comma between them).
You’ll see ... called the spread operator too. Same syntax, opposite job: spread expands an array into separate values, a rest parameter gathers separate values into an array.
In our case we can also shorten this using the implicit return syntax available in arrow functions:
const join = (...strings) => strings.join('')
and we can call this in the same way we did before:
join('hi', ' flavio') // 'hi flavio'
join('hi', ' flavio', ' it', ' is', ' a', ' beautiful day!') // 'hi flavio it is a beautiful day!'
Mixing named and rest parameters
You can have normal parameters before the rest one. The rest parameter collects everything left over:
const logOrder = (customer, ...items) => {
console.log(customer, items)
}
logOrder('Flavio', 'pizza', 'coke')
// 'Flavio' [ 'pizza', 'coke' ]
One rule to remember: the rest parameter must be the last one. Writing (...items, customer) is a syntax error, because JavaScript would have no way to know where the collected arguments end.
Before rest parameters existed, we used the arguments object for this. It’s array-like but not a real array, so no .join() or .map() without converting it first, and it’s not available in arrow functions at all. Rest parameters replaced it for good reasons: use them instead.
Related posts about js: