Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSwan The Human
Full Stack JavaScript Techdegree Student 19,338 PointsCould anyone give me a real world example of the use of rest params? What would this be used for
I understand why you would want to use the spread operator for concatenation of arrays but what would you use the rest param in functions for? I get the usage of it but it makes it more clear and useful with an example of one thing you would use it for. Thanks!
1 Answer
Steven Parker
231,236 PointsRest parameters are essentially the opposite of spread syntax. Instead of expanding an array into individual arguments, an unspecified number of individual arguments are folded into an array. Example:
// use REST parameter to output any number of messages
function logger(...msgs) {
console.info(`Logging ${msgs.length} messages:`)
for (msg of msgs)
console.log(msg);
}
logger("message one", "message two");
logger("this", "is", "a", "test");
More details and another good example of usage can be found on the MDN Rest Parameters page.