Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
function total(...numbers) {
  return numbers.reduce((sum, n) => sum + n, 0);
}

Try it

JS Collecting extra arguments

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Rest in destructuring

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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. rest has all array methods (map(), filter(), reduce()), unlike arguments.
  • Always an array. With no extra arguments you get [], never undefined.
  • Works in arrow functions, which have no own arguments object.
  • length ignores it. A function's length property counts only the parameters before the rest parameter, so total.length is 0.
  • 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, Set and 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 arguments never did.

Browser support

Rest parameters and array destructuring rest are supported in all current browsers. Object rest properties work in every current browser too.