Hello! In our last lesson, we explored how the three dots (...) can be used as the spread operator to expand or unpack elements from arrays and objects. Today, we'll look at the other side of this powerful syntax.
This lesson focuses on the rest parameter. While it looks identical, its function is the exact opposite: to collect multiple function arguments and bundle them into a single array. This allows you to create highly flexible functions that can accept a variable number of inputs, a common requirement for utility functions you'll build on your path to learning Next.js.
Your goal for this lesson is to learn how to use the rest parameter (...) to collect multiple function arguments into an array.
What is the Rest Parameter?
The rest parameter ... gathers an indefinite number of arguments into an array. Think of it as the inverse of the spread operator:
- Spread Operator: Unpacks a single array into multiple individual elements.
- Rest Parameter: Packs multiple individual arguments into a single array.
A great analogy is to think of the rest parameter as a vacuum cleaner. When you call a function with a list of arguments, the rest parameter sucks up all the remaining items and neatly stores them in an array for you to use.
How to Use the Rest Parameter
You use the rest parameter in a function's definition. The syntax is three dots ... followed by the name you want to give to the array that will hold the arguments.
Let's watch a short video that introduces the basic syntax and contrasts it with the spread operator we learned about previously.
#45 What is the Rest Parameter? | JavaScript Full Tutorial
This clip from Dev Dreamer will walk you through the core concept of the rest parameter and show a simple example of how it gathers arguments into an array.
Watch from 00:22 to 02:21. Pay close attention to how a function without a rest parameter ignores extra arguments, and how adding ... solves this problem by collecting them.
As the video demonstrated, if you define a function like function sum(a, b), calling it with sum(1, 2, 3, 4) will simply ignore the 3 and 4.
By using the rest parameter, we can create a function that handles any number of arguments:
// The '...numbers' syntax collects all arguments into an array called 'numbers'.
function sumAll(...numbers) {
let total = 0;
// We can now loop over the 'numbers' array.
for (const num of numbers) {
total += num;
}
return total;
}
console.log(sumAll(1, 2)); // Output: 3
console.log(sumAll(10, 20, 30, 40)); // Output: 100
console.log(sumAll(5)); // Output: 5
Key Rule: The Rest Parameter Must Be Last
A critical rule is that the rest parameter must be the last parameter in a function's definition. This makes logical sense—it's meant to collect "the rest" of the arguments after all named parameters have been assigned.
You can have regular, named parameters before the rest parameter. JavaScript will assign arguments to the named parameters first, and then bundle everything else into the rest parameter's array.

Let's see this in action.
#45 What is the Rest Parameter? | JavaScript Full Tutorial
This next clip from the same Dev Dreamer video demonstrates how to use named parameters alongside the rest parameter.
Watch from 03:59 to 05:14. Notice how the first two arguments are assigned to x and y, while z becomes an array containing all subsequent arguments.
Here is a code example illustrating the concept:
function showTeam(coach, captain, ...players) {
console.log(`Coach: ${coach}`);
console.log(`Captain: ${captain}`);
console.log(`Players: ${players.join(', ')}`);
}
showTeam("Ms. Davis", "Alice", "Bob", "Charlie", "Dana");
// Output:
// Coach: Ms. Davis
// Captain: Alice
// Players: Bob, Charlie, Dana
If you try to place a named parameter after a rest parameter, JavaScript will throw a syntax error.
// This will cause an error!
function wrongSyntax(...players, coach) {
// ...
}
Test your understanding!
Write a function called logScores. It should accept a playerName as its first argument and an indefinite number of scores as the rest of its arguments. The function should then log a message to the console that says: "[playerName]'s scores are: [scores]".
For example, logScores("Alex", 95, 88, 100) should output: "Alex's scores are: 95,88,100".
Show answer
function logScores(playerName, ...scores) {
// The 'scores' parameter is now an array, e.g., [95, 88, 100].
// We can use array methods on it, like .join() or .toString().
console.log(`${playerName}'s scores are: ${scores.toString()}`);
}
// Example usage:
logScores("Alex", 95, 88, 100);
logScores("Maria", 75, 82);
Explanation:
- The function defines
playerNameas the first parameter to capture the first argument passed. - The rest parameter
...scorescollects all subsequent arguments into a true JavaScript array namedscores. - Inside the function, we can use
scoresjust like any other array. In this case,scores.toString()automatically converts the array[95, 88, 100]into the string"95,88,100".
Deep Dive: Rest Parameters vs. The arguments Object
Before ES6 introduced rest parameters, JavaScript had another way to access all function arguments: a special, built-in object called arguments. You might see this in older code or articles.
While arguments seems similar, the rest parameter is superior for several key reasons. Understanding this will give you the "under the hood" knowledge you're looking for.
Rest parameters and spread syntax
This article from javascript.info provides a concise explanation of the old arguments object and why rest parameters are the modern, preferred approach.
Read the section titled 'The “arguments” variable'. Focus on the downsides it mentions: it's 'array-like' but not a true array, and it always contains all arguments.
To summarize the key differences and why ...rest is better:
- It's a Real Array: The rest parameter gives you a true array. This means you can immediately use powerful array methods like
.map(),.filter(), and.reduce(). Theargumentsobject is only "array-like" and lacks these methods, requiring an extra step to convert it into a real array first. - It Captures Only "The Rest": The rest parameter lets you separate leading arguments from the rest. The
argumentsobject always contains every argument passed to the function, making it less flexible. - Works in Arrow Functions: The special
argumentsobject does not exist inside arrow functions, but rest parameters work perfectly. Since arrow functions are central to modern JavaScript (which we'll cover soon), this makes rest parameters essential.
Practical Examples
Let's look at a couple more practical examples to see how flexible the rest parameter can be.
JavaScript REST PARAMETERS in 8 minutes! 🗄
The video from Bro Code demonstrates two great use cases: calculating an average from any number of scores and combining multiple strings into a full name.
Watch from 03:49 to 07:31. For the getAverage example, notice how the function uses .length on the numbers array, which is possible because the rest parameter creates a true array. For the combineStrings example, see how the .join() array method is used to easily create a full name from separate parts.
These examples reinforce the power of receiving arguments as a true array, allowing you to leverage JavaScript's built-in array methods to write clean and efficient code.
Conclusion
You have now mastered both uses of the versatile ... syntax. By understanding the context in which it's used, you can easily distinguish between them.
Key Takeaways:
- The rest parameter (
...) is used in a function's parameter list to collect an indefinite number of arguments into a single, true array. - It provides a flexible way to create functions that can handle varying numbers of inputs, like a math utility (
sumAll,getAverage) or a string formatter. - The rest parameter must be the last parameter in a function definition.
- It is the modern and superior replacement for the older
argumentsobject because it creates a real array and works with arrow functions.
Rest vs. Spread (A Final Summary):
function myFunc(...args) {}-> REST: Gathers arguments into anargsarray.myFunc(...myArray)-> SPREAD: ExpandsmyArrayinto individual arguments.
Next Up
In our next lesson, we will dive into another cornerstone of modern JavaScript: arrow functions. You will learn their concise syntax and, more importantly, understand how their handling of the this keyword differs from regular functions, a crucial concept for your journey into Next.js and React.