Rest parameter (...rest)

Collects all the remaining function arguments into a real array. You write it as ...name at the end of the parameter list.

On this page

Example

#
JavaScript
function totalPoints(...scores) {
  return scores.reduce((sum, score) => sum + score, 0)
}

console.log(totalPoints(10, 20, 30))
console.log(totalPoints(5))
console.log(totalPoints())
Console
60
5
0

Definition and usage

#

You write a rest parameter as three dots before the name of the last parameter: function sum(...numbers). Every argument that didn’t land in an earlier parameter ends up in it as a plain array. When there are no such arguments, the array is empty, not undefined.

That makes it easy to write a function that accepts any number of values: summing points, joining CSS class names, or logging an event with extra data. It’s a real array, so you immediately have map(), reduce(), and length at your disposal.

The rest parameter must come last, and there can only be one. It replaces the older arguments object, which isn’t an array and doesn’t exist in arrow functions. The same three dots at a function call, fn(...array), mean spread, the reverse operation: spreading an array out into separate arguments.

Syntax

#
Syntax
function name(...rest) {}
function name(first, second, ...rest) {}
const fn = (...args) => {}

More examples

#
A fixed parameter plus the rest
JavaScript
function logEvent(type, ...details) {
  console.log(type, details.length, details)
}

logEvent('lesson', 'CSS', 'Grid')
logEvent('login')
Console
lesson 2 ['CSS', 'Grid']
login 0 []
Rest vs. spread
JavaScript
function maxScore(...scores) {
  return Math.max(...scores)
}

const results = [72, 95, 88]

console.log(maxScore(...results))
console.log(maxScore(40, 60))
Console
95
60

In the definition, ...scores collects the arguments into an array (rest), and in the call Math.max(...scores) spreads the array out into separate arguments (spread).

Instead of the deprecated arguments object
JavaScript
function oldStyle() {
  console.log(Array.isArray(arguments), arguments.length)
}

function newStyle(...args) {
  console.log(Array.isArray(args), args.length)
}

oldStyle('a', 'b')
newStyle('a', 'b')
Console
false 2
true 2

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • The rest parameter always goes last. Writing function fn(...items, last) is a syntax error.
  • Don’t use arguments in new code. The rest parameter gives you a real array and also works in arrow functions.
  • When a function takes several optional settings of different kinds, a single options object with destructuring is more readable than a long argument list.

Related entries

#

Spotted a mistake or missing an example? Write to us.