Categories
JavaScript Answers

How to Accept an Unlimited Number of Arguments in a JavaScript Function?

Spread the love

Sometimes, we want to accept an unlimited number of arguments in a JavaScript function.

In this article, we’ll look at how to accept an unlimited number of arguments in a JavaScript function.

Accept an Unlimited Number of Arguments in a JavaScript Function

To accept an unlimited number of arguments in a JavaScript function, we can use the rest operator in the function signature.

For instance, we write:

const foo = (a, b, ...others) => {
  console.log(a, b);
  for (const val of others) {
    console.log(val);
  }
}

foo(1, 2, 3, 4, 5);

We have the foo function that has the parameters a , b , and others .

others has the 3 dots before it, which is the rest operator.

The 3rd and subsequent arguments that are passed into foo will be put into the others array.

Therefore, a is 1, b is 2, and the for-of loop will log 3, 4, and 5.

Conclusion

To accept an unlimited number of arguments in a JavaScript function, we can use the rest operator in the function signature.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *