The Rest Parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

Is used to get the arguments list passed to function on invocation and in array destructure. A case when the operator gathers the rest remained after the operation.

Rest is an instance Array so he can use all Array methods like `.filter()`, '.map()` etc...

Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments.

Destructuring rest parameters

Rest parameters can be destructured, that means that their data can be extracted into distinct variables.

Example

function f(...[a, b, c]) {
  return a + b + c;
}

f(1)          // NaN (b and c are undefined)
f(1, 2, 3)    // 6
f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)

Array Destructuring

As a part of the destructuring, the rest operator extracts parts of an array. The extraction result is always an array.

Example

var seasons = ['winter', 'spring', 'summer', 'autumn'];  
var coldSeason, otherSeasons;  
[coldSeason, ...otherSeasons] = seasons;
console.log(coldSeason);   // => 'winter'  
console.log(otherSeasons); // => ['spring', 'summer', 'autumn']

Rest parameter

The function declarationfunction sumOnlyNumbers(...args)indicates thatargsreceives the invocation arguments in an array. Because the names conflict is solved,argscan be used insidefilterNumbers().

Example

function sumOnlyNumbers(...args) {  
  var numbers = filterNumbers();
  return numbers.reduce((sum, element) => sum + element);
  function filterNumbers() {
     return args.filter(element => typeof element === 'number');
  }
}
sumOnlyNumbers(1, 'Hello', 5, false); // => 6

Notice that rest parameter should be last one in the function parameters list.

Example

function multiply(multiplier, ...theArgs) {
  return theArgs.map(function (element) {
    return multiplier * element;
  });
}

var arr = multiply(2, 1, 2, 3); 
console.log(arr); // [2, 4, 6]

Selective rest parameter

If not all values should be included in the rest parameter, you could define those as comma separated parameters at the beginning. Explicitly defined parameters are not included in the rest parameter.

function filter(type, ...items) {  
  return items.filter(item => typeof item === type);
}
filter('boolean', true, 0, false);        // => [true, false]  
filter('number', false, 4, 'Welcome', 7); // => [4, 7]

results matching ""

    No results matching ""