JavaScript Spread Syntax Explained

Eren Akbulut
Dev Genius
Published in
3 min readFeb 5, 2021

--

Image by Quang Nguyen vinh from Pixabay

Hello everyone, today I’ll briefly explain what JavaScript spread syntax is and where can we use them. It’s going to be a fairly shorter one since there isn’t much to cover around the topic but I do believe that the spread syntax is now essential for everyone who writes JavaScript no matter how often they do that. You can find the examples that are about to be shared here.

What is spread?

“Spread 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.” is the definition from the MDN Web Docs. Everything is cool but where can we actually use it, maybe we should show that on the examples.

Here we are creating an array called array1 and passing the elements of the array as arguments with the help of the spread operator.

Creating a new array with additional members is also quite simple, we can also decide the newMember’s place just by changing the position.

This is one of my favorite use cases for the spread, as you can see above instead of using the “concat” method we can simply use spread.

Here above we have another use that can be quite handy at times, we can place an older one into another when creating a new array.

Even though the spread is quite useful for most cases it’s still good to be cautious at times, JavaScript is a flexible language, and that kinds of error are quite possible.

This time we’ll take a look at use on the objects, we first create 3 objects and with those 3 we create 2 new objects. As we can see above when the keys are conflicting spread will always override the old one with the new one, otherwise, it’ll just create a new object with all key-value pairs.

Conclusion

The spread syntax is a huge convenience for JS developers and since I assume that everyone who writes some JS now knows about a spread I tried to keep the guide as beginner-friendly as possible. We can maybe cover some popular use cases of spread with mainstream technologies like React or Vue or something like that.

Alright everyone, thanks for reading so far. I hope to see you at the next one. Take care :)

Originally published at https://blog.akbuluteren.com.

--

--