Rest (...)
Collects remaining function arguments or destructured elements into an array or object.
Syntax
function fn(...args) {}
const [first, ...rest] = array;
const { a, ...others } = object;
Examples
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4));
Output
10
const [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail);
Output
1 [ 2, 3, 4 ]
const { id, ...rest } = { id: 1, x: 2, y: 3 };
console.log(rest);
Output
{ x: 2, y: 3 }
Notes
- A rest parameter must be the last parameter and gives a real array
(unlike `arguments`).
- Object rest in destructuring collects remaining own enumerable
properties (ES2018).
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 47 |
| firefox | 15 |
| safari | 10 |
| edge | 12 |
| node | 6.0 |