Skip to content

How to accept unlimited parameters in a JavaScript function

New Course Coming Soon:

Get Really Good at Git

How is it possible to have a function that accepts an unlimited number of parameters?

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 the 2 arguments we pass:

join('hi', ' flavio') // 'hi flavio'

One simple 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.

Instead, we can use this syntax, with the spread operator (...) followed by the name of the parameter we want to use. Inside the function, the parameter is an array, so we can simply call its .join() method to concatenate the strings it contains, passing an empty string as argument (otherwise it defaults to concatenate strings adding a comma between them):

const join = (...strings) => {
  return strings.join('')

In our case we can also simplify 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!'
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: