ECMA 6 Spread Operator & Rest parameters
/* The spread operator 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.
Spread takes a collection of something, like [] s or {} s, and applies them to something
else that accepts , separated arguments, like function s, [] s, and {} s.
*/
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);
/* Today if you have an array and want to create a new array with the existing
one being part of it, the array literal syntax is no longer sufficient and you have to
fall back to imperative code, using a combination of push, splice, concat, etc.
With spread syntax this becomes much more succinct:*/
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders", "knees", "and", "toes"]
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
let mapABC = { a: 5, b: 6, c: 3};
let mapABCD = { ...mapABC, d: 7}; // { a: 5, b: 6, c: 3, d: 7 }
/* The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
If the last named argument of a function is prefixed with ...,
it becomes an array whose elements from 0 to theArgs.length are supplied by
the actual arguments passed to the function.
*/
function(a, b, ...theArgs) {
// ...
}
/*
Technically JavaScript already had an arguments variable set on each function (except for
arrow functions), however arguments has a lot of issues, one of which is the fact that it is
not technically an array.
Difference between rest parameters and the arguments object
There are three main differences between rest parameters and the arguments object:
rest parameters are only the ones that haven't been given a separate name,
while the arguments object contains all arguments passed to the function;
the arguments object is not a real array, while rest parameters are Array instances,
meaning methods like sort, map, forEach or pop can be applied on it directly;
the arguments object has additional functionality specific to itself (like the callee property).
function print(a, b, c, ...more) {
console.log(more[0]);
console.log(arguments[0]);
}
print(1, 2, 3, 4, 5);
// 4
// 1
*/
function fun1(...theArgs) {
console.log(theArgs.length);
}
fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3