JavaScript — Using The Spread Operator (…)

Waqar Bin Kalim
3 min readMar 18, 2022

--

A simplified look at how to use the Spread Operator (…) in JavaScript

Introduction

On the MDN Web Docs, it says “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.

… that’s a lot of complicated stuff, right? Well, I’ll try to summarize it for you. And hopefully, by the end of this article, you’ll know how to use the spread operator.

Photo by Lautaro Andreani on Unsplash

How To Use The Spread Operator

The spread can be used in three different ways:

  1. For a function call
  2. For an array
  3. For an object

Although you’ll most often use it in an object or array, it’s still useful to know how to use it in a function call. And I’ll go over each of these in detail below.

For a function call

The ‘spread’ operator, as its name implies, spreads open the values. In the case of using the spread operator when calling a function, you call it as myFunction(...args). And in the body of the function, you can use the args variable as a regular array with each element inside the array as one of the entered arguments.

An example of the spread operator being used in a sum function

For an array

The spread operator can also be used for an array. Again, as the name implies, it spreads open the values. And you can use this spread operator in arrays to concatenate arrays and to deep copy arrays. And I’ll show you how to do both of these tasks.

An example of the spread operator being used to concatenate arrays and to add items to arrays
An example of the spread operator being used to deep copy arrays

For an object

The spread operator can also be used for an object. And again, as the name implies, it spreads open the values. Objects can be merged using the spread operator, just like arrays. In addition to that, the spread operator can be used to update properties within an object.

An example of the spread operator being used to merge objects
An example of the spread operator being used to update properties in an object

Conclusion

The spread operator can be used in all sorts of ways and I highly recommend getting familiar with it. The spread operator is essentially syntactic sugar, but when used correctly, it can make your code cleaner and enhance readability. Trust me, spend around 30 minutes googling around about the spread operator and you’ll thank me.

Hope this article helps you understand the Spread operator (…). Please let me know if you believe I misunderstood something, and I will make the necessary changes to the article. Thank you!

--

--