// the old way
function foo (a, b) {
b = b || 'bar';
return a + b;
}
// the ES6 way!
function foo (a, b='bar') {
return a + b
}
foo('baz') // => 'bazbar'
foo('baz', 'quux') // => 'bazquuz'
function foo (a, ...args) {
// much easier and more descriptive than Array.prototype.slice.call!
args.forEach(arg => {
console.log(a + arg);
});
}
foo(1, 2) // => 3
foo(1, 2, 3) // => 3 4
// maybe more realistic example
function createMiddleware (...middlewares) {
return function (action) {
middlewares.forEach(middleware => middleware(action));
};
}
// cleaner than Function.prototype.apply
function foo (a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
let arr = [1, 2, 3];
foo(...arr); // same as foo.apply(foo, arr);
// declaratively flatten arrays
let numbers = [1, 2, 3];
let letters = ['a', 'b', 'c'];
let both = [...numbers, ...letters];
console.log(both); // => [ 1, 2, 3, 'a', 'b', 'c' ]
// for strings, the spread operator is an alternative to String.prototype.split
let string = "Hello";
console.log([...string]); // => [ 'H', 'e', 'l', 'l', 'o' ]
// here we're using ... in a function definition - so this is the rest parameter
function createMiddleware (...middlewares) {
// this is also a function definition - rest parameter
return function (...args) {
// now we're using it with a function invocation - this is the same as
// middleware.apply(null, args)
middlewares.forEach(middleware => middleware(...args));
};
}