DEV Community

Cover image for Understanding the Spread Operator(...) in JavaScript
Brandon Damue
Brandon Damue

Posted on • Updated on

Understanding the Spread Operator(...) in JavaScript

In today's episode of talking about awesome JavaScript features, we are going to turn our attention to the Spread operator(...) or Spread syntax. At the end of this article, you'll find a curated list of the links to other articles I have written in the past on some other JavaScript concepts and features. In the meantime, let us focus on the Spread operator(...), what it is all about and how to use it to write better JavaScript code.

The Spread syntax is a JavaScript feature that allows objects and iterables (such as arrays and strings) to be unpacked, or expanded, which can be used to make shallow copies of data structures to increase the ease of data manipulation. It is often used in combination with destructuring.

What is the Spread operator used for?

This operator can be used to carry out many routine tasks easily. The spread operator can be used to do the following:

  • Copying an array

  • Concatenating or combining arrays

  • Using Math functions

  • Using an array as arguments

  • Adding an item to a list

  • Combining objects

Let's look at an example of each of these use cases.

Copying an array

Using the Spread operator is a convenient way to copy an array or combine arrays, and it can even add new items.

const animals = ['🦁','🐘','🐈','πŸ•β€πŸ¦Ί','πŸ‡']
const moreAnimals = [...animals];
console.log(moreAnimals) // Array(5) ['🦁','🐘','🐈','πŸ•β€πŸ¦Ί','πŸ‡']
Enter fullscreen mode Exit fullscreen mode

Combining or Concatenating arrays

The spread operator can be used to quickly combine two arrays.

const myArray = [1,2,3];
const yourArray = [4,5];
const ourArray = [...myArray,...yourArray];

console.log(ourArray); // Array(5) [ 1, 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

Using Math functions

In my opinion, the best way to understand the use of the spread operator is to look at the built-in functions Math.min() and Math.max(), which both expect a list of arguments, not an array. Suppose you have an array of numbers and want to get the smallest or largest number in that array, you will have to make use of Math.min() or Math.max() but passing an array to any of these functions will return NaN which isn't the answer you'd be hoping for. Instead, you should use the (...) operator to expand the array as a list of arguments in the Math function as demonstrated in the example below:

const numbers = [28, -6, 19, 0]
console.log(Math.min(numbers)) // NaN
console.log(Math.min(...numbers)) // -6
console.log(Math.max(...numbers)) // 28
Enter fullscreen mode Exit fullscreen mode

Using an array as arguments

You can use the spread operator to turn an array into a list of arguments. See the example below:

function sandwich(a, b, c) {
  console.log(a); // '🍞'
  console.log(b); // 'πŸ₯¬'
  console.log(c); // 'πŸ₯“'
}

const food = ['🍞', 'πŸ₯¬', 'πŸ₯“'];

// Old way
sandwich.apply(null, food);

// βœ… ES6 way
sandwich(...food);
Enter fullscreen mode Exit fullscreen mode

Adding an item to a list

The spread operator can add an item to another array with a natural, easy-to-understand syntax:

const numbers = [1, 2, 3, 4]
const moreNumbers = [...numbers, 5, 6, 7, 8]

console.log(moreNumbers) // Array(8) [1, 2, 3, 4, 5, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

Combining objects

Watch how the spread operator combines these two objects:

const myVehicle = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'red'
}

const updateMyVehicle = {
  type: 'car',
  year: 2021, 
  color: 'yellow'
}

const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
Enter fullscreen mode Exit fullscreen mode

Notice the properties that did not match were combined, but the property that did match, color, was overwritten by the last object that was passed, updateMyVehicle. The resulting color is now yellow.

Conclusion

The advent of ES6 did not only make JavaScript more efficient but also more fun with the introduction of cool features like the spread operator and others. Below is the curated list of articles I promised at the beginning of this write up.

Top comments (14)

Collapse
 
bcostaaa01 profile image
Bruno

Really great article, @brandonbawe!πŸ‘

I found it very nice that you gave a list of points where the spread operator is useful πŸ‘Œ

One thing I would add would be, in the Math functions section, that you can use the spread operator to pass array elements as arguments to a function in more use cases. One example would be calling a function with an array of arguments:

function sum(a, b, c, d) {
    return a + b + c + d;
}

let arr = [1, 2, 3, 4];
let result = sum(...arr);
console.log(result); // 10
Enter fullscreen mode Exit fullscreen mode

This is the same as if you would be calling the sum function with (1, 2, 3, 4) as β€œhardcoded” arguments.

Keep it up!πŸ™Œ

Collapse
 
brandondamue profile image
Brandon Damue

Thank you for your input Bruno. It is highly appreciated.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
brandondamue profile image
Brandon Damue

Thank you for you review Abhay. The Spread operator is really an awesome feature that makes JavaScript more fun to work with.

Collapse
 
mcsee profile image
Maxi Contieri

nice examples!

Collapse
 
brandondamue profile image
Brandon Damue

Thank you Maxi

Collapse
 
neumatic_78 profile image
neu-ma-tic

spread is good but i find does not work recursively. try lodash merge function

Collapse
 
brandondamue profile image
Brandon Damue

Okay I'm going to try that out. Thank you for your input.

Collapse
 
mahbubdev1 profile image
Munir Uddin Mahbub

yes, It's Good for me , Thank you so much

Collapse
 
brandondamue profile image
Brandon Damue

You are welcome Munir.

Collapse
 
munyanezaarmel profile image
Munyaneza Armel

Thank you for sharing

Collapse
 
9opsec profile image
9opsec

Good explanation of something that has been confusing for me!

Collapse
 
tejus07 profile image
Tejus Sahi

That's Great Article, i learned something new about spread operator use case.
Math.min and Math.max i think its really useful.

Collapse
 
brandondamue profile image
Brandon Damue

Thank you for your review sir.