// maybe you've seen...
function foo (a, b) {
b = b || 'bar';
return a + b;
}
function foo (a, b) {
if (b === undefined) b = 'bar';
return a + b;
}
now we don't need to include default values as part of the function logic!
// the ES6 way!
function foo (a, b='bar') {
return a + b
}
allows us to represent an indefinite number of arguments as an array
aggregates the remaining arguments into a single parameter (helpful for variadic functions!)
function(a, b, ...theArgs) {
// ...
}
function foo (a, ...args) {
// much easier and more descriptive than Array.prototype.slice.call!
args.forEach(arg => {
console.log(a * arg);
});
}
foo(2, 1, 2, 3, 4, 5) // => 2, 4, 6, 8, 10
//using array methods on the rest parameters
function sortRestArgs(...theArgs) {
var sortedArgs = theArgs.sort();
return sortedArgs;
}
console.log(sortRestArgs(5,3,7,1)); // => 1,3,5,7
The spread syntax allows an expression to be expanded in places where...
multiple arguments (for function calls) or
multiple elements (for array literals) or
multiple variables (for destructuring assignment)
are expected.
function foo (a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
let arr = [1, 2, 3];
// we could use Function.prototype.apply...
foo.apply(null, arr);
// or we could use spread
foo(...arr);
let numbers = [1, 2, 3];
let letters = ['a', 'b', 'c'];
// we could use Array.prototype.concat...
// but if we use the spread operator we can easily declaratively flatten arrays
let both = [...numbers, ...letters]; => [1, 2, 3, 'a', 'b', 'c']
// or we can add things to the middle of an array
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
// => ["head", "shoulders", "knees", "and", "toes"]
// now we don't have to do parts.splice(1, 0, lyrics);
// for strings, the spread operator is an alternative to String.prototype.split
let string = "Hello";
console.log([...string]); // => [ 'H', 'e', 'l', 'l', 'o' ]