Categories
JavaScript Answers

How to pass an unknown number of arguments into JavaScript function?

Spread the love

Sometimes, we want to pass an unknown number of arguments into JavaScript function.

In this article, we’ll look at how to pass an unknown number of arguments into JavaScript function.

How to pass an unknown number of arguments into JavaScript function?

To pass an unknown number of arguments into JavaScript function, we use the rest operator.

For instance, we write

const printNames = (...names) => {
  for (const name of names) {
    console.log(name);
  }
};

to define the printNames function that takes an infinite number of arguments.

We use the ... rest operator to get all the arguments into the names array.

Then we use a for-of loop to loop through all the names entries and print out all the entries into the console.

Conclusion

To pass an unknown number of arguments into JavaScript function, we use the rest operator.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.