JavaScript Rest Parameters
Rest parameters gather the extra arguments of a function into one array. A function with rest parameters accepts any number of extra arguments.
Gather the extra arguments
Three dots before the last parameter name mark rest parameters. The extra arguments arrive as one array.
function sum(...numbers) {
let total = 0;
for (const n of numbers) {
total += n;
}
return total;
}
console.log(sum(1, 2, 3, 4));Rest with named parameters
Named parameters take the first arguments. Rest parameters gather the rest.
function greet(first, ...others) {
console.log(first);
console.log(JSON.stringify(others));
}
greet("Asha", "Ben", "Cara");An empty rest array
A call with no extra arguments gives an empty array. Rest parameters are always an array.
function count(...items) {
return items.length;
}
console.log(count());
console.log(count("one"));Example
function joinWords(separator, ...words) {
return words.join(separator);
}
console.log(joinWords("-", "red", "green", "blue"));
console.log(joinWords(" ", "one", "two"));Key points
- Rest parameter: three dots before the last parameter name, like ...args
- The extra arguments arrive as one array.
- Named parameters before the rest parameter take the first arguments.
- A call with no extra arguments gives an empty array.
- Use rest parameters to write a function that accepts any number of arguments.
In this example, joinWords takes a separator and then any number of words. The rest parameter gathers the words into one array. The join call builds one string from that array.
Note
A function can hold only one rest parameter, and it must be last.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does ...args collect in function f(...args)?