The Rest Parameter
The rest parameter (...) collects multiple elements into a single array. It looks the same as the spread operator but works in the opposite direction: spread expands, rest collects.
Rest is mainly used in function parameters and destructuring to gather remaining values.
function greet(first, ...rest) {
console.log(first); // 'Hello'
console.log(rest); // ['World', '!']
}
greet('Hello', 'World', '!');
You can use the rest parameter during array destructuring to assign the first few values to variables and collect the remaining ones into an array.
const [first, second, ...others] = [10, 20, 30, 40, 50];
console.log(first); // 10
console.log(second); // 20
console.log(others); // [30, 40, 50]
first and second get individual values, while others collects everything that remains.
The rest parameter must always be the last element in the parameter list or destructuring pattern. You cannot have anything after it.
// Correct: rest is last
function example(a, b, ...rest) {
console.log(a, b, rest);
}
example(1, 2, 3, 4, 5);
// Output: 1 2 [3, 4, 5]
// Wrong: rest is NOT last (this will throw a SyntaxError)
// function wrong(...rest, last) {} // SyntaxError
Putting something after the rest parameter causes a SyntaxError. Rest must always come at the end.
Rest also works in object destructuring. You can extract specific properties and collect the remaining ones into a new object.
const person = { name: 'Alice', age: 25, city: 'Paris', job: 'Developer' };
const { name, age, ...details } = person;
console.log(name); // 'Alice'
console.log(age); // 25
console.log(details); // { city: 'Paris', job: 'Developer' }
name and age are extracted directly, and details gets all the remaining properties.
The rest parameter is very useful when you want a function to accept any number of arguments. The collected values come in as a real array, so you can use array methods on them.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
You can also mix fixed parameters with a rest parameter:
function introduce(greeting, ...names) {
names.forEach(name => console.log(`${greeting}, ${name}!`));
}
introduce('Hello', 'Alice', 'Bob', 'Charlie');
// Hello, Alice!
// Hello, Bob!
// Hello, Charlie!
-
The rest parameter (
...) collects remaining values into an array. - Use it in array destructuring to capture leftover elements.
- Use it in object destructuring to gather remaining properties.
- Rest must always be the last item in the parameter list or destructuring pattern.
- It enables functions to accept any number of arguments in a clean way.
- The collected values form a real array, so all array methods work on them.