When I first stumbled upon the ... operator it looked confusing and I didn't really know what to do with it. Javascript already had built in functions that were doing the exact same thing as this new operator so the need to integrate it in my code wasn't very clear to me. Today, after I used it for quite a while, it's one of my favorite ES6 features and it helps me manipulate arrays and strings much easier than before.
MDN says that:
"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."
Pretty simple, no? In plain English this means that this operator spreads the items inside an iterable (be it string, array, set or anything that we can loop through really) inside a receiver (a receiver is something that receives the spread values).
Now that we got the definition out of the way, what exactly can we do with this operator?
2. Copy an array and add new elements to it
This works with arrays holding different types or mixed arrays, like so.
4. Spread elements on function calls
6. Concatenate and add new properties to object literals
Image source: negativespace/ @negativespace on Pexels
Discussion (6)
Awesome post! I always had a hard time understanding this one but your definition made much more sense than the MDM docs :)
After reading your post, there's one thing I'd note. It looks like the operator actually copies the contents of the object/array/whatever instead of just assigning it by reference. For example:
This returns false because they are now two different copies, not a reference to each other. In fact this is the reason why in React its recommended to update state using the spread operator (or concat if its an array) as you are not modifying the original value but making a new one.
Yes,
obj === {...obj}
returns false because they are different copies, but look at the code below:The property
x
was copied by value, but the propertiesy
andz
were copied by reference.Nice article with good examples
I recently came accross the spread operator too - yet to try it out though. Your post nicely explains it.
Great one!
Tip: You should try carbon.now.sh for code screenshots. They look pretty cool
Do you know pattern matching in functional programming? It's way more advanced.