Coming soon!

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

  • javascript
  • Ecmascript2015

By Joris Brauns · 9/9/2016 4:06:51 PM (Original Post)

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!


  • javascript
  • Ecmascript2015

By Joris Brauns · 9/9/2016 4:06:51 PM (Original Post)

Share this blogpost

Looking for talent?

Fill in the form below and we’ll get back to you as soon as possible.

Oops. You seem to have written your full name in invisible ink. Please enter it so we can read it. Oops. You seem to have written your company in invisible ink. Please enter it so we can read it. It seems your e-mail doesn’t exist. Please enter a real one so we can contact you. Oops. You seem to have written your telephone in invisible ink. Please enter it so we can read it.