JavaScript Reference ยท Function
Rest parameters
Reference for JavaScript rest parameters (...args): collect remaining arguments into a real array, combine with named parameters and compare with arguments.
A rest parameter, written ...name, collects all remaining arguments of a call into a real array. It lets a function accept any number of values without using the old arguments object.
Do not confuse it with spread syntax. Both use three dots; rest gathers values in a parameter list or destructuring pattern, while spread expands values in a call or array.
function total(...numbers) { return numbers.reduce((sum, n) => sum + n, 0); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
function f(a, b, ...rest) {} const g = (...rest) => {}; const [x, ...others] = array; const { key, ...remaining } = object;
Rules:
| Rule | Description |
|---|---|
| Position | The rest element must be the last one. function f(...a, b) is a SyntaxError. |
| Only one | A parameter list can have only one rest parameter. |
| No default | A rest parameter cannot have a default value; it is an empty array when nothing is left. |
| Trailing comma | A trailing comma after a rest parameter is a syntax error. |
Usage notes
- A real array.
resthas all array methods (map(),filter(),reduce()), unlikearguments. - Always an array. With no extra arguments you get
[], neverundefined. - Works in arrow functions, which have no own
argumentsobject. lengthignores it. A function'slengthproperty counts only the parameters before the rest parameter, sototal.lengthis0.- Object rest copies the remaining own enumerable properties into a new plain object; it is a shallow copy and skips properties already taken by earlier names.
- Array rest takes the remaining items from the iterable's position, so it also works with strings,
Setand generators. - Passing an array in: use spread when calling, as in
total(...list). - Style: a rest parameter makes the "any number of arguments" intent obvious in the signature, which
argumentsnever did.
Browser support
Rest parameters and array destructuring rest are supported in all current browsers. Object rest properties work in every current browser too.