There are lots of different ways that this becomes useful. One way is it allows you to easily make a copy of an array or object. Since the spread operator spreads out the contents of a collection into a list of arguments we can then easily put them back into a 'new' collection. This is easily done by preceding what you want to copy with '...'. Lets look at a simple example:
Here I added to my copy array and you can see that when I log the original array, it's values remain unaltered. Now let's see what happens if I didn't make a copy:
Now when I add to my copy array, the value is also added to the original array therefore mutating it. This can lead to unintended consequences and the spread operator can ensure this won't happen! .Slice() is nice but spread wins the bread!😎
Another helpful way to use the spread operator is to combine two or more arrays. Instead of using the .concat method just prefix the array with '...'. Check it out:
Here I'm still using the animals array but this time I also made an otherAnimals array. To combine them I just used the spread operator within an array literal and voila! Now I've got a whole new array that contains both of their values, easy peasy! You can also add other items in addition to combining two or more arrays. Why .concat() when you can just spread! 🐱🏍
This copying technique also works with objects. You can combine two or more objects using the spread syntax just like how we did with arrays. This is very similar to using Object.assign().
Another thing to watch out for when using this technique with objects is, which Dr. Derek Austin points out in the same blog referenced earlier, "any properties whose names conflict will be lost." If this occurs, the first object's property value will be replaced by the second object's value.
Here you can see when I log combinedAnimalsObject, the property value for sheep gets replaced with "baah".
Without using the spread syntax we get nasty NaN 😢.
In conclusion the spread operator is a very simple, useful tool! It can be used to make shallow copies of collections and to combine arrays or objects with ease. It's also helpful when you have an array you want to use as a function argument but your function only takes individually listed parameters. I hope this helps! Thanks for reading!
Top comments (0)