Skip to content

Latest commit

 

History

History
76 lines (62 loc) · 2.13 KB

2.10.Rest-Parameters.md

File metadata and controls

76 lines (62 loc) · 2.13 KB

2.10 -- ES6 Rest parameters: Default Parameters, Rest Parameters, Spread Operator, Destructured Parameters

Replaces the need for using arguments to access functions arguments and allows you to get to an array representing "the rest of the parameters". Rest parameters are a collention of parameters

function allTogether(...onlyOne){
  onlyOne.forEach(function(onlyOne){
     console.log(onlyOne);
  })
}
allTogether('1','2','3','4','5');

Default parameter values: =

We can now set defaults when defining arguments

function f(x, y=10, z=20) { 
  // y is 10 and z is 20 if not passed (or passed as undefined) 
  console.log(x , y , z); // 3 10 20
  console.log(x + y + z); // 33
  return x + y + z; 
} 
console.log( f(3) == 33 )

Ej1: Default parameter values

Rest parameters values: ...

Replaces the need for using arguments to access functions arguments. It allows you to get to an array representing "The rest of parameters".

function multiply(multiplier, ...theArgs) {  // multiplier = 2 and [theArgs]
  console.log(multiplier + ' and: '+ theArgs); // 2 - 1,2,3  
}

var arr = multiply(2, 1, 2, 3);  

Ej1: Rest using map

Spread parameters values

spread operator:

let arr = [-1, 7, 2, null, -0, +0, 10, 21];
let highest = Math.max(...arr);
console.log(arr); // 
console.log(highest);

Ej1: spread operator

spread operator: (...) as parameters

function restParameters(param, ...params) {
  return params;
}
console.log(restParameters('a', 'b', 'c')); // ['b', 'c']

Ej1: spread operator as parameter

Spread Operator: (...) to turn strings into Arrays

let chars = [...'Jon' + 'Doe'];
console.log(chars); // ["J", "o", "n", "D", "o", "e"]

Spread Operator: Default function parameters

Allow formal parameters to be initialized with default values if no value or undefined is passed.

function foo(n, nn = 'test') {
  console.log(n,nn)
}
foo(1); // 1 "test"