AI Workshop: learn to build apps with AI →
JavaScript Recipes: Unlimited Function Parameters

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


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 function that accepts two strings:

const join = (string1, string2) => {
  return string1 + string2
}

and when we call it, we get a string that is the concatenation of the two 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.

Rest Parameters

Instead, we can use the rest parameter syntax (...) 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 the separator (otherwise it defaults to concatenating strings with 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!'

Lessons in this unit:

0: Introduction
1: Generate Random Numbers in a Range
2: Get Index in for...of Loop
3: ▶︎ Unlimited Function Parameters
4: Return Result from Async Function
5: Encode and Decode URLs
6: Destructuring Tips
7: Number Formatting
8: Regex Recipes
9: Dynamic function name in JS