JavaScript
Flexible parameters with rest
Learn to combine the rest parameter with destructuring and how it differs from the arguments object.
The rest parameter
The rest parameter is also written with three dots, but this time on the parameter side of a function definition. Writing function sumAll(...numbers) makes numbers a real array holding every incoming argument.
The old arguments object is not an array; .map or .reduce do not work on it. The rest parameter is a full array, so every array method is available. That is why modern code prefers rest.
Rest in destructuring
Rest also works inside destructuring. Writing const [first, ...rest] = colors makes first take the first element; rest holds the rest as a new array.
The same idea works for objects: const { name, ...others } = user splits off name and gathers every remaining property into others. Rest must always be in the last position.
Exercise Flexible word joiner
Write a function called joinWords(separator, ...words). The first parameter is a separator string; then any number of word arguments follow. Use the .join(separator) method of the words array to combine all words and return the result. Then call the function with at least three words and log it with console.log.
Show example solution
function joinWords(separator, ...words) {
return words.join(separator);
}
console.log(joinWords("-", "apple", "pear", "cherry"));
Test yourself
-
What does the rest parameter do?
function sumAll(...numbers) {
return numbers.length;
}
- It accepts only a single argument
- It ignores all parameters
- It is a deprecated syntax
- It collects incoming arguments as a real array
Show answer
It collects incoming arguments as a real array — Correct. Rest collects an array; that is what sets it apart from arguments.
-
Match the rest usages
- ...args (parameter)
- Collects remaining arguments
- ...rest (destructuring)
- Collects remaining elements
- real array
- Type of the rest parameter
-
Complete the function signature
function sumAll(____) {
let total = 0;
for (const n of numbers) total += n;
return total;
}
console.log(sumAll(1, 2, 3));
Show answer
function sumAll(...numbers) {
let total = 0;
for (const n of numbers) total += n;
return total;
}
console.log(sumAll(1, 2, 3));
Next lesson: Copying with spread