Rest and Spread operators `...` in ES6
ES6 added two important new operators: Rest and Spread. Technically they look the same ( … => three dots) but they are used in different places.
Rest & Spread Operators …
ES6 added two important new operators: Rest and Spread. Technically they look the same ( … => three dots) but they are used in different places. Same markup but can be used in different/opposite way.
Rest operator
The rest operator transforms a list of arguments into an array.
function sumUp(start, ...toAdd) {
console.log(...toAdd); // => [1,2,3,4,5,6] create an array
}
sumUp(1, 1,2,3,4,5,6);
In the above code, the rest operator will transform the list of arguments like (1, 2, 3, 5, 6) into an array ([1, 2, 3,4, 5, 6]) which may be used inside the function, sumUp.
PS: This behavior is triggered when used inside of a function argument list.
Another example:
function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2));
console.log(howMany("string", null, [1, 2, 3], { }));
In the above code, the function howMany()
can accept any type and number of arguments. In the first console.log, there are 3 arguments while in the second console.log there will be 4 arguments.
The rest parameter eliminates the need to check the
args
array and allows us to applymap()
,filter()
andreduce()
on the parameters array.
Spread operator
The spread operator will break an array onto a list of items
let ids = [1, 2, 3, 4, 5, 6];
console.log(...ids); => 1 2 3 4 5 6
console.log(Math.max(...ids)); // => 6
Transforms an array into a list of arguments. This behavior is triggered when used outside of a function argument list. In the example above, the spread operator is used as a method parameter.
Please note:
For an array:
const arr = [1,2,3,4,5,6,7];
console.log(...arr) => unpacked array, only a list of values
...arr
returns an unpacked array. In other words, it spreads the array. However, the spread operator only works in-place, like in an argument to a function or in an array literal.
The following code will not work:
const spreaded = ...arr;
Instead:
const spreaded = [...arr]; => this will create a new array named spreaded which is an exact copy of arr