JavaScript Rest Parameters
Table of Contents + โ
In the previous lesson, we learned how the spread operator expands a list of values out of an array or object. Now letโs look at rest parameters, which use the same ... symbol to do the opposite: gather many values into one array.
๐ฆ What are Rest Parameters?
A rest parameter collects all the leftover arguments passed to a function and bundles them into a single array. You write it by placing ... before the parameter name in the function definition. This lets a function accept any number of arguments without knowing how many will arrive.
function showAll(...items) { console.log(items);}
showAll("a", "b", "c"); // ["a", "b", "c"]showAll(1, 2); // [1, 2]showAll(); // []Letโs walk through what each line does:
function showAll(...items)declares one rest parameter nameditems, so whatever arguments arrive get gathered into a real array.console.log(items)prints that array, showing exactly what was collected.showAll("a", "b", "c")passes three values, soitemsbecomes["a", "b", "c"].showAll(1, 2)passes two values, soitemsbecomes[1, 2].showAll()passes nothing, soitemsbecomes an empty array[].
โ Summing Any Number of Values
Because the gathered arguments form a real array, you can loop over them or use array methods directly. Here is a function that adds up however many numbers you give it.
function sum(...numbers) { let total = 0; for (const number of numbers) { total += number; } return total;}
console.log(sum(1, 2, 3)); // 6console.log(sum(10, 20, 30, 40)); // 100console.log(sum(5)); // 5Letโs break down how this adds everything up:
function sum(...numbers)collects every argument into thenumbersarray.let total = 0starts a running total at zero.for (const number of numbers)walks through each value in the array one at a time.total += numberadds the current value onto the running total.return totalhands back the final sum, sosum(1, 2, 3)gives6,sum(10, 20, 30, 40)gives100, andsum(5)gives5.
๐ฏ A First Argument Plus the Rest
A common pattern is to name one or two regular parameters first and then collect everything else with a rest parameter. The named parameters fill up first, and the rest parameter takes whatever is left over.
function greet(greeting, ...names) { return names.map((name) => `${greeting}, ${name}!`);}
console.log(greet("Hello", "Alex", "Sam", "Jordan"));// ["Hello, Alex!", "Hello, Sam!", "Hello, Jordan!"]Here is what each part contributes:
greetingcaptures the first argument,"Hello"....namesgathers all the remaining arguments into the array["Alex", "Sam", "Jordan"].names.map((name) => ...)builds a new array by combininggreetingwith each name.- The result is one greeting string per name, returned as an array.
๐ Spread vs Rest
The ... symbol does two opposite jobs depending on where it appears. Spread expands an array into separate values, while rest gathers separate values into an array.
| Feature | Spread | Rest |
| What it does | Expands one array into many values | Gathers many values into one array |
| Where it is used | In a function call or array literal | In a function definition or destructuring |
| Example | sum(...[1, 2, 3]) | function sum(...nums) |
An easy way to remember
If ... is on the receiving side of a function definition, it is rest. If it
is on the giving side, spreading values into a call or array, it is spread.
๐งฉ Rest in Destructuring
Rest also works when you destructure an array. You can pull out the first few items by name and collect everything else into a new array.
const scores = [90, 85, 70, 60];
const [first, ...others] = scores;
console.log(first); // 90console.log(others); // [85, 70, 60]Letโs trace what this unpacks:
const scores = [90, 85, 70, 60]sets up the array we will split.const [first, ...others] = scorespulls the first item intofirstand gathers the remaining items intoothers.firstholds90, the single value at the front.othersholds[85, 70, 60], a new array of everything left over.
โ ๏ธ Common Mistakes to Avoid
| Mistake | Problem | Solution |
| Putting the rest parameter before others | function f(...nums, last) is a syntax error | The rest parameter must be the last one |
| Confusing rest with spread | Using ... in the wrong place changes its meaning | Rest gathers in a definition; spread expands in a call |
Treating the old arguments object like an array | arguments is array-like, so methods like map fail | Use a rest parameter, which is a real array |
A modern replacement
Older code used a special arguments object to read extra arguments. Rest
parameters give you a true array instead, so you can use methods like map,
filter, and reduce right away.
๐ง Try It Yourself!
- Write a function
sum(...numbers)that returns the total of any number of values, and test it with two, three, and four numbers. - Write a function that takes a first label argument plus a rest parameter, then returns a sentence using both.
- Use array destructuring with
...to split an array into its first item and the rest. - Try putting the rest parameter before a regular parameter and read the error message JavaScript gives you.
๐งฉ What Youโve Learned
- โ
A rest parameter uses
...to collect extra arguments into a single array - โ It lets a function accept any number of arguments
- โ The rest parameter must always be the last parameter
- โ
Spread expands values, while rest gathers them, even though both use
... - โ
Rest also works in destructuring, like
const [first, ...others] = arr
๐ Whatโs Next?
Now that you understand functions and values fully, we will step into the browser and start working with web pages. Letโs continue to What is DOM.