...

/

Tip 31: Passing Variable Number of Arguments with Rest Operator

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.

Press + to interact
function validateCharacterCount(max, items) {
return items.every(item => item.length < max);
}

Notice the every() method? It’s another simple array method you haven’t seen before. As with filter(), you pass a callback that returns a truthy or falsy value. The every() method returns true if every item in an array passed to the callback returns truthy. Otherwise, it returns false.

Running the function is simple. Just pass in an array of strings.

Press + to interact
function validateCharacterCount(max, items) {
return items.every(item => item.length < max);
}
console.log(validateCharacterCount(10, ['Hobbs', 'Eagles']));

Communicating parameters

The code above is great because it’s so generic. You can easily reuse it elsewhere. The only down side to this code is that it locks the users of your function into a particular collection type. Another developer might, for example, want to test that a single username isn’t too long. To use the code, they’d have ...

Access this course and 1400+ top-rated courses and projects.