Let’s say you want to concatenate two arrays.

Bad Practice

This way, you will mutate your original array. You won’t be able to access your original array again. It’s hard to read. Loops are efficient but really hard to read due to their imperative nature. Hard to maintain. What if you need to concatenate a third array? Or a fourth one?

Best Practice

Wow! What happened here? We concatenated two array using the spread operator (triple dot syntax).

JavaScript interpreter will read “ array3 is an array containing every arr1 and arr2 element” (such a declarative approach!).

But what else can you do with this awesome operator?

Creating a new array from zero

You can easily create a new array of N elements in one line:

But hey, every created value is undefined!

Yes, they are! That’s because you are just creating an array on N elements without defining what every single element is.

How is it useful?

In the previous episode we talked about the .map method: using both . map and spread operator, we can easily create (as an example) an array of numbers:

This is powerful!

Copying Objects by value

Thanks to the spread operator, we can easily coping objects by value instead of reference. Let me explain that:

Wait wait wait! Why does obj1.one return 2 ? I updated copy ‘s one property, not the obj1 ‘s one!

False! We explicitly said that copy is bound to obj1 . Everytime we update copy structure, we also alterate obj1 , and that’s terrible!

We can easily solve this problem using the spread operator: instead of passing obj1 by reference, we’ll just copy all of its keys and values inside of the copy object.

That way, once we mutate any copy key, we’ll leave unchanged the original obj1 object.

Function Arguments

In ES5, this was a common practice:

If you wanted to use an array as a function argument, you had to use the Function.prototype.apply method.

In ES6 you can easily achieve that by using the spread operator:

And what if you want to get every single function argument without knowing how many arguments you’ll receive?

And now let’s combined everything we’ve learnt so far!

Wow! At first this seems to be a little complicated, but now I bet that you’re reading and enjoying it!