The question itself already brings two of these improvements, right? Well, almost. In fact, the second example is quite different from the first.
The first example shows what is called the spread operator (*): It comes to the left of a list (a # , usually an array) and spreads or "unfolds" its contents into distinct variables. In your example, the list items are distributed as arguments at the time of the 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 parameter list of a function, ...
does not distribute a list in values, but instead collects the values in a list:
function myFunc(name, ...args) { } // args coleta todos os argumentos passados depois de name
This is often called rest parameters , or other parameters. At the signature of the function, they can only appear at the end. Regardless of the name, it is 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 the spread operator , it has other uses than what you showed in the first example. In literal arrays, it allows you to concatenate and interpolate 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 destructor operation ( destructuring , very interesting feature, a bit like the list
of PHP, but more powerful):
[a, ...outros] = [1,2,3,4];
// a = 1
// outros = [2, 3, 4]
Finally, it still allows you to do something that required some 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 neither listed as an operator; the grammar of the language treats ...
literally, and distinguishes the semantics of the spread and the rest according to the context.