ES6 JavaScript Rest Parameter

ES6 JavaScript “Rest parameters” are used in function definitions to convert an indefinite number of arguments (e.g. 1,2,3,4) into an Array (e.g. [1,2,3,4]) to be used in the function body. Examples below | MDN docs

My ES6 JS Rest Parameter Cheatsheet Animated GIF

JavaScript ES6 Rest Parameter Animation


My ES6 JS Rest Parameter Tutorial Video (posted 4/11/19)


ES6 JS Rest Parameter Examples

as sole parameter:

You can use a rest parameter to capture all passed arguments into an array:

1
2
3
4
5
6
7
8
9
// 1) called with an indefinite number of arguments:
doWork('a', 'whole', 'lotta', 'args');

// 2) you can define a function that will gather all
// the arguments into an array
function doWork(...myArgsArray) { // 'rest' parameter
console.log(myArgsArray);
// ['a', 'whole', 'lotta', 'args']
}

as last parameter

You can capture a few ‘named arguments’ first and then gather all the rest of the arguments in an array with a final rest parameter. NOTE: The rest parameter must be the final parameter or you will have a syntax error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 1) called with an indefinite number of arguments:
doWork('a', 'whole', 'lotta', 'args');

// 2) and the first few args are important so you'll have a few 'named' arguments
// and then collect the 'rest' in an array named inputArray like so:
function doWork(arg1, arg2, ...myArgsArray) { // MUST be the final parameter
console.log(arg1);
console.log(arg2);
console.log(myArgsArray);

// 'a'
// 'whole'
// ['lotta', 'args']
}

“Rest Parameter” vs “Arguments” Object:

There is also a traditional arguments object people also use for things like this, but there are important differences:

  1. It is an object not an Array so you would have to convert it to an Array first before using any Array methods.
  2. It always holds ALL the arguments. With rest parameters we can control which of arguments make it into the array e.g. function doWork(arg1, arg2, ...inputArray){} // arg1 and arg2 are not included

‘rest’ vs ‘spread’ Rule of Thumb:

If you see ...varName in a function DEFINITION e.g. function fn(a1, a2, ...others){}, it’s a ‘rest’. Elsewhere, it’s a ‘spread’.

Share