A quick post to write about one of my favourite ES6 features - Spread operator.
What is it?
Official (and frankly boring) definition from Mozilla docs:
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
I don't blame you for dozing off after reading that definition. It doesn't necessarily enthuse you or inform you of its usefulness. Let me show you some practical use cases on this amazing operator and the fun you can have with it.
Example 1: Merge / Concat two arrays
Using spread to concat two arrays and create a new array
Example 2: String is also an iterable that can be spread inside an array
You can take a string and break it down to its constituent parts.
Example 3: Copy an array by spreading it into a new array variable
Use spread operator to copy the values to another array easily.
Example 4: Convert a nodelist into an array
When you query an element from the document object, it typically returns a nodelist - which is an array-like structure but not an Array and therefore doesn't have functions like map or forEach. You can use Array.from() to convert the nodelist into an Array or you can use a spread operator as shown below to achieve the same outcome as shown below.
Example 5: The Rest Param
The Rest Param has nothing to do with the REST (Representational State Transfer) architecture style. It simply shows an alternate use of the spread operator specifically used in the context of Function parameters.
I hope these examples give you an idea of how useful the spread operator is. Until next time.
Thanks for taking the time to read this post, if you found it useful and if you have any comments or tips, please hit me up on Twitter (@anup).