How to accept unlimited parameters in JavaScript functions

How to have a function that can accept an infinite number of parameters?

Suppose we have a file namedjoin()His job is to join all the strings we pass to it.

For example, we wrote a prototype that accepts 2 strings:

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

When we call it, we get a string that is the concatenation of the two parameters we passed:

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

An easy way is to append other parameters that are appended to the empty string by default, as shown below:

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

But this method does not scale well because we need to add a lot of parameters, and our code looks very bad.

Instead, we can use this syntax and use the spread operator...), and then the name of the parameter we want to use. Inside the function, the parameter is an array, so we can simply call it.join()The method of concatenating the contained strings and passing an empty string as a parameter (otherwise, by default, multiple strings are concatenated and a comma is added between them):

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

In our case, we can also simplify this operation using the implicit return syntax available in arrow functions:

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

We can call it as before:

join('hi', ' flavio') // 'hi flavio'
join('hi', ' flavio', ' it', ' is', ' a', ' beautiful day!') // ''hi flavio it is a beautiful day!'

Download mine for freeJavaScript beginner's manual


More js tutorials: