Ecmascript 6 Features 5: Spread and Rest
Unfortunately I have been rather busy this week so far, but I managed to find time to write up another post for you. This week's ES6 features are spread and rest. They go hand in hand, so I thought I would cover them both at once.
Spread
The spread operator lets you spread an array's contents out as the arguments when calling a function. It works like Function.apply, but it looks much neater :)
function multiply(a, b, c)
{
return a * b * c;
}
var numbers = [4, 7, 2];
console.log(multiply(...numbers)); // 56
Before you might have had to do something like this:
console.log(multiply.apply(this, numbers)); // 56
Personally, I think that the new addition make a lot more sense than the old apply function, although you will still need to use Function.apply() if you want to customise the execution context of the function.
Rest
The spread operator, as you might expect, spread an array of things out to different arguments. But what if you wanted to bunch them back up again? ES6 can handle that too, through the rest operator. The rest operator allows you to bunch the rest of the arguments passed to a function into an array:
function log_adv(who, ...what)
{
"use strict";
var str = `[ ${new Date().toLocaleString()} ] [ ${who} ] `;
for(let thing of what)
{
str += JSON.stringify(thing) + " ";
}
console.log(str);
}
var x = Math.random(),
y = Math.random() * 2;
// Logs something like:
// [ 08/07/2015, 11:51:14 ] [ program ] "x is" 0.051463941344991326 "y is" 1.5026674889959395
log_adv("program", "x is", x, "y is", y);
So there you have it! Two more new features of ES6. Next time I might look into arrow functions. Also, this Friday I will be posting about a PHP hashtag-to-title converter that I wrote for a project that I am working on for someone I know.