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');
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 )
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);
let arr = [-1, 7, 2, null, -0, +0, 10, 21];
let highest = Math.max(...arr);
console.log(arr); //
console.log(highest);
function restParameters(param, ...params) {
return params;
}
console.log(restParameters('a', 'b', 'c')); // ['b', 'c']
Ej1: spread operator as parameter
let chars = [...'Jon' + 'Doe'];
console.log(chars); // ["J", "o", "n", "D", "o", "e"]
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"