The question itself already brings two of these improvements, right? Well, almost. Actually, the second example is quite different from the first.
The first example shows what is commonly called Operator spread (*): it comes to the left of a list (a Iterable, usually an array) and spreads or "unfolds" its contents into distinct variables. In your example, list items are distributed as arguments at the time of function call:
var max = Math.max(...[1, 2, 3]); // equivale a Math.max(1, 2, 3)
In ES5, as you noticed, this is only possible with apply
, which is much less readable.
The second example has the opposite semantics: in the list of parameters of a function, the ...
does not distribute a list in values, but rather collects the values in a list:
function myFunc(name, ...args) { } // args coleta todos os argumentos passados depois de name
This is usually called Rest Parameters, or other parameters. In function signature, they can only appear at the end. Regardless of the name, it’s clearly a syntax improvement because it eliminates the need for slice.call(arguments, n)
within the function, which would be required in ES5.
Returning to Operator spread, it has other uses than what you showed in the first example. In literal arrays, it allows concatenating and interpolating arrays:
let umaArray = [3, 4];
let outraArray = [6, 7];
let combo = [1, 2, ...umaArray, 5, ...outraArray];
// combo = [1, 2, 3, 4, 5, 6, 7]
It can also be used on the left side of a breakdown operation (destructuring, very interesting feature, somewhat similar to the list
PHP, but more powerful):
[a, ...outros] = [1,2,3,4];
// a = 1
// outros = [2, 3, 4]
Finally, it still allows to do something that required a certain juggling in ES5, a kind of apply
combined with new
:
new Date(...[2015,7, 31]);
The equivalent in ES5 was this "beauty" here:
new (Date.bind.apply(Date, [null, 2015, 7, 31]));
References
(*) In the specification this is not even listed as an operator; the grammar of the language treats the ...
literally, and distinguishes the spread and Rest semantics according to the context.
Liked, pretty explanation :D
– Wallace Maxters
The part that I found more interesting is the "combo". I hadn’t thought about this use.
– Wallace Maxters