Spread Operator

This blog post is mostly a mental note to myself. As I always forget the name of this sweet syntax of merging arrays and function parameter calls together in JavaScript. This is part of the new feature in Ecmascript2015.

The main objective of the spread operator is to spread the objects of an array.
Let's directly dive to some code and show you some examples to get a better idea.

Copy an array
var arr = [1,2,3]; var arr2 = [...arr]; // like arr.slice()
r2.push(4); // arr2 becomes [1,2,3,4], arr stays unaffected

Or even better, how often do you use the push? In ES5 this is often done as:
Merge array with push:
var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5];
// Append all items from arr2 onto arr1 Array.prototype.push.apply(arr1, arr2);

In ES6 with spread this becomes:
var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5];
arr1.push(...arr2);

And there is even more, you can even apply it on function calls!
For example:
function f(a, b, c, x, y, z) { return a + b + c + x + y + z; } var args = [1, 2, 3];
console.log(f(...args, 4, ...[5, 6]));
// Output: 21

Hopefully it useful for you as well, I found this very handy and only learned it just a few weeks ago which is a pity!