Tip 31: Passing Variable Number of Arguments with Rest Operator

In this tip, you’ll learn to collect an unknown number of parameters with the rest operator.

In the previous tips, you saw how object destructuring would let you combine several parameters into a single argument.

Handling an unknown number of parameters

Using objects to hold parameters is a great technique, but it’s really only useful in situations where the parameters are different and you know them ahead of time. In other words, it only makes sense in situations with objects.

That may seem obvious, but it raises the question: How do you handle an unknown number of similar parameters?

Think back to the photo display application. What if you wanted to allow your users to tag photos but you only wanted the tags to be a certain length? You could easily write a very short validation function that takes a size and an array of tags and returns true if all are valid.

Get hands-on with 1200+ tech skills courses.