JavaScript: Function Rest Parameters

By Xah Lee. Date: . Last updated: .

New in JS2015.

A function can have unspecified number of parameters, like this:

function ff (...name) { return name; }

That is, 3 dots followed by a name. In function body, the name is received as a array.

This is called β€œrest parameters”.

The syntax ...name must be the last in the parameter declaration. Space after the dots is optional.

The syntax ...name can only happen once.

// rest params, with arrow with function

const ff = ((...rr) => rr);

console.log(
  JSON.stringify(ff(1, 2, 3, 4)) === "[1,2,3,4]",
);
// function with any number of parameters

function ff(...rr) {
  return rr;
}

console.log(
  JSON.stringify(ff(1, 2, 3, 4)) === "[1,2,3,4]",
);
// rest params as last arg
function ff(a, b, ...c) {
  return c;
}

console.log(
  JSON.stringify(ff(1, 2, 3, 4)) === "[3,4]",
);

If no rest parameter is given, value is a empty array.

// rest params, if no arg given, value is empty array
console.log(JSON.stringify(((...rr) => rr)()) === "[]");

JavaScript Function

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc