JavaScript Rest Parameters

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.

rest-parameters.js
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 named items, 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, so items becomes ["a", "b", "c"].
  • showAll(1, 2) passes two values, so items becomes [1, 2].
  • showAll() passes nothing, so items becomes 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.

rest-parameters.js
function sum(...numbers) {
let total = 0;
for (const number of numbers) {
total += number;
}
return total;
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
console.log(sum(5)); // 5

Letโ€™s break down how this adds everything up:

  • function sum(...numbers) collects every argument into the numbers array.
  • let total = 0 starts a running total at zero.
  • for (const number of numbers) walks through each value in the array one at a time.
  • total += number adds the current value onto the running total.
  • return total hands back the final sum, so sum(1, 2, 3) gives 6, sum(10, 20, 30, 40) gives 100, and sum(5) gives 5.

๐ŸŽฏ 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.

rest-parameters.js
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:

  • greeting captures the first argument, "Hello".
  • ...names gathers all the remaining arguments into the array ["Alex", "Sam", "Jordan"].
  • names.map((name) => ...) builds a new array by combining greeting with 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.

rest-parameters.js
const scores = [90, 85, 70, 60];
const [first, ...others] = scores;
console.log(first); // 90
console.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] = scores pulls the first item into first and gathers the remaining items into others.
  • first holds 90, the single value at the front.
  • others holds [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!

  1. Write a function sum(...numbers) that returns the total of any number of values, and test it with two, three, and four numbers.
  2. Write a function that takes a first label argument plus a rest parameter, then returns a sentence using both.
  3. Use array destructuring with ... to split an array into its first item and the rest.
  4. 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.

Share & Connect