ES6 Sampler #4 : Spread ...

October 19, 2016


JavaScript

Preface

Pssst... Previous ES6 Samplers
Note - Challenges: I gave myself little challenges you are welcome to try if you want to recreate my own learning curve.

Let's start:

I’ve been bitting my nails for this one, The spread syntax is all kinds of awesome, but what is it and what does it replace ?

Challenge: Find out what the spread syntax does and what it replaces
From the docs - Syntax for function Calls:
myFunction(...iterableObj);

See the Pen ES6 Sampler - Spread Operator Pt1. by Eugenio - Keno - Leon (@k3no) on CodePen.

More than anything, the spread syntax brings clarity and a cool way of using enumerable arguments in a function call. There seems to be more, you can also use them in array literals, but what does that entail…

Challenge: Find out how to use the spread syntax in a Array Literal and it's counterpart in es5
From the docs - Syntax for array literals:
[...iterableObj, 4, 5, 6]

See the Pen ES6 Sampler - Spread Operator Pt2. by Eugenio - Keno - Leon (@k3no) on CodePen.

Notice that depending how you use those 3 dots it is either a spread ( wave your hand like you are spreading something on bread), or Rest ( as in the rest of), Operator.

Challenge: Find out other uses of the spread syntax

See the Pen ES6 Sampler - Spread Operator Pt3. by Eugenio - Keno - Leon (@k3no) on CodePen.

One of the coolest things you can do with the dots, are Rest Parameters, so you can define a function with an unlimited/unknown number of parameters.

All together now:

Coding Test: Use the spread syntax in a function call,array literal and with function parameters

See the Pen ES6 Sampler - Spread Operator Pt4 by Eugenio - Keno - Leon (@k3no) on CodePen.

Conclusion

You can use the spread syntax to simplify your javascript in a lot of places and cases, each one has it’s nuances, but overall make writing clear JS easier.

TL;DR:

Spread Syntax has many faces all of them are useful

Best,

Keno.