Eren Akbulut's Blog

JavaScript Spread Syntax Explained

February 5th, 2021

js-spread-peacock

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 an 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.


js-spread-function
  • Here we are creating an array called array1 and passing the elements of the array as arguments by the help of spread operator.

js-spread-addnewelement
  • Creating a new array with additional members is also quite simple, we can also decide the newMember's place just by changing the position of it.

    js-spread-ccat
  • 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.

js-spread-anothernewarray
  • Here above we have another use that can be quite handy at times.

js-spread-none-spread
  • 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.

js-spread-obj
  • This time we'll take a look at a 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

Spread syntax is a huge convenience for JS developers and since I assume that everyone who writes some JS is now knows about 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 in the next one. Take care :)

This blog has been created by Eren Akbulut 2020