DEV Community

Cover image for 10 ways to use the spread operator in JavaScript
Chris Bongers
Chris Bongers

Posted on • Updated on • Originally published at daily-dev-tips.com

10 ways to use the spread operator in JavaScript

I'm sure you've heard of the spread operator in JavaScript (...), it's one of the most powerful operators JavaScript offers and can solve many problems like the 10 you will find below.

The spread operator can be used to solve multiple problems you might encounter in JavaScript.
In this article, you will learn how to do the following operations by the use of the spread operator.

In the basic form, the spread operator looks like three dots.

[...arr];
Enter fullscreen mode Exit fullscreen mode

Copy an array

We can use the spread operator to copy an array, this is however still a shallow clone.

Let's say we have an array called arr1 and we want to make a clone of this array called arr2.

const arr1 = [1,2,3];
const arr2 = [...arr1];
console.log(arr2);
// [ 1, 2, 3 ]
Enter fullscreen mode Exit fullscreen mode

So this way we can copy a basic array, be aware it doesn't work for multi-level arrays or arrays with dates or functions.

Using the spread operator to copy an array

Note: Read more about deep-cloning in JavaScript

Combine arrays

Let's say you have two arrays that you want to merge into one, this happens quite often and we could use the concat method.
The spread operator just makes this way easier as you can see below.

const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
// [ 1, 2, 3, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode

So now the two arrays (arr1, arr2) are combined into arr3.

You can state which one should come first by arranging them differently.

const arr3 = [...arr2, ...arr1];
console.log(arr3);
[4, 5, 6, 1, 2, 3];
Enter fullscreen mode Exit fullscreen mode

This is a good way to combine arrays, the amount you can add is infinite so you can just keep adding spread operators.

const output = [...arr1, ...arr2, ...arr3, ...arr4];
Enter fullscreen mode Exit fullscreen mode

Combining arrays using the spread operator

Add an item to an array

Let's say you have an array, but you need to add one or multiple items to it.
You can leverage the Array.push but the spread operator will also work just fine.

let arr1 = ['this', 'is', 'an'];
arr1 = [...arr1, 'array'];
console.log(arr1);
// [ 'this', 'is', 'an', 'array' ]
Enter fullscreen mode Exit fullscreen mode

As you can see this will add the new string to the end of our existing array.

You can even pass multiple strings.

arr1 = [...arr1, 'array', 'cool'];
console.log(arr1);
// [ 'this', 'is', 'an', 'array', 'cool' ]
Enter fullscreen mode Exit fullscreen mode

Add an item to an array

Adding a property to an object

Let's say you have an object of a user, but it's missing an age property.

const user = {
  firstname: 'Chris',
  lastname: 'Bongers'
};
Enter fullscreen mode Exit fullscreen mode

To add the age to this user object, we can again leverage the spread operator.

const output = {...user, age: 31};
Enter fullscreen mode Exit fullscreen mode

What happens above is that we spread the user object and add a new property called age to it with the value of 31.

The whole setup will look like this.

const user = {
  firstname: 'Chris',
  lastname: 'Bongers'
};
const output = {...user, age: 31};
console.log(output);
// { firstname: 'Chris', lastname: 'Bongers', age: 31 }
Enter fullscreen mode Exit fullscreen mode

Adding a property to an object using the spread operator

Use Math() functions

Let's say you have an array of numbers and you want to either get the lowest, highest, or the sum of these numbers.

That's another great option for the spread operator to shine.

Our input array will look like this

const arr1 = [1, -1, 0, 5, 3];
Enter fullscreen mode Exit fullscreen mode

To get the lowest number we can use the spread operator and the Math.min method.

const arr1 = [1, -1, 0, 5, 3];
const min = Math.min(...arr1);
console.log(min);
// -1
Enter fullscreen mode Exit fullscreen mode

This will output -1 because that's the lowest number, try and remove the -1 from the array you'll see the lowest will become 0.

To get the highest number we can use the Math.max method.

const arr1 = [1, -1, 0, 5, 3];
const max = Math.max(...arr1);
console.log(max);
// 5
Enter fullscreen mode Exit fullscreen mode

As you can see the max will return 5, if we remove the 5 it will return 3.

If you're curious to see what happens if we don't spread:

const arr1 = [1, -1, 0, 5, 3];
const max = Math.max(arr1);
console.log(max);
// NaN
Enter fullscreen mode Exit fullscreen mode

This will return NaN because JavaScript doesn't know what to max on an array.

Using math functions by leveraging the spread operator

Spread array as function arguments

Let's say we have a function that takes three arguments.

const myFunc(x1, x2, x3) => {
    console.log(x1);
    console.log(x2);
    console.log(x3);
}
Enter fullscreen mode Exit fullscreen mode

We could call this function in the following manner:

myFunc(1, 2, 3);
Enter fullscreen mode Exit fullscreen mode

But what happens if we have an array that we want to pass.

const arr1 = [1, 2, 3];
Enter fullscreen mode Exit fullscreen mode

We can now use the spread operator to spread this array into our function.

myFunc(...arr1);
// 1
// 2
// 3
Enter fullscreen mode Exit fullscreen mode

As you can see we spread the array into three separate arguments that we pass to the function.

The full call will look like this:

const myFunc = (x1, x2, x3) => {
  console.log(x1);
  console.log(x2);
  console.log(x3);
};
const arr1 = [1, 2, 3];
myFunc(...arr1);
// 1
// 2
// 3
Enter fullscreen mode Exit fullscreen mode

Using the spread operator to pass an array as arguments

Pass unlimited arguments to a function

Let's say you have a function that takes unlimited arguments, perhaps they are properties you want to dynamically loop over.

const myFunc = (...args) => {
  console.log(args);
};
Enter fullscreen mode Exit fullscreen mode

If we now call this function with multiple arguments we see the following happening.

myFunc(1, 'a', new Date());
Enter fullscreen mode Exit fullscreen mode

It will return the following:

[
  1,
  'a',
  Date {
    __proto__: Date {}
  }
]
Enter fullscreen mode Exit fullscreen mode

We are then able to dynamically loop over the arguments.

Accepting unlimited arguments using the spread in a function

Converting a nodeList into an array

Let's say you used the spread operator to get all the divs on your page. These will come as a nodeList.
We can then leverage the spread operator to convert this nodeList into an array.

const el = [...document.querySelectorAll('div')];
console.log(el);
// (3) [div, div, div]
Enter fullscreen mode Exit fullscreen mode

Here you can see we got three divs from the dom.

We can now easily loop over these elements because they are in an array format.

const el = [...document.querySelectorAll('div')];
el.forEach(item => {
  console.log(item);
});
// <div></div>
// <div></div>
// <div></div>
Enter fullscreen mode Exit fullscreen mode

Note: If you want to learn more about looping over nodeList results check out this article.

Convert nodeList results into an array

Destructuring an object

If you're familiar with destructuring objects you might find the spread operator to be very useful to do this.

Let's say we have an object for the user again.

const user = {
  firstname: 'Chris',
  lastname: 'Bongers',
  age: 31
};
Enter fullscreen mode Exit fullscreen mode

We can now destructure this as single variables using the spread operator.

const {firstname, ...rest} = user;
console.log(firstname);
console.log(rest);
// 'Chris'
// { lastname: 'Bongers', age: 31 }
Enter fullscreen mode Exit fullscreen mode

As you can see we parsed the user object and destructured the firstname into the firstname variable and the rest of the object into the rest variable.

Destructure objects with spread

Exploding a string

The last use-case for the spread operator is to explode a string.

Let's say we have the following string.

const str = 'Hello';
Enter fullscreen mode Exit fullscreen mode

If we then use the spread operator on this string we will get an array of letters.

const str = 'Hello';
const arr = [...str];
console.log(arr);
// [ 'H', 'e', 'l', 'l', 'o' ]
Enter fullscreen mode Exit fullscreen mode

There you go, an array of letters.

Exploding strings with the spread operator

I also live-streamed how I'm writing this article you can view the recording on Youtube:

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (15)

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Pass unlimited arguments to a function

I see this pattern a lot here on dev. People try to use simple vocabulary, so even beginners can understand the article, but never really mention the correct vocabulary. How do I google more about this thing I just learned if I don't know it's called a variadic function?

Collapse
 
dailydevtips1 profile image
Chris Bongers

I don't even know it's called a variadic function, and never googled it that way, still, get around by googling pass unlimited arguments...

I understand there's are official names for these things, but no beginner will know these or remember these, that's not my goal for this article.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

but no beginner will know these

And that's precisely why I think they should be named in articles like this, because knowing the right name for a thing is just as important as knowing it exists.

"unlimited arguments" is both longer and more ambiguous than "variadic". The latter has a clear meaning in programming, so I can bring them up in a conversation and everyone is on the same page, but if I say "unlimited arguments", I'd have to explain what I mean.

Collapse
 
jdnichollsc profile image
J.D Nicholls

Take care of the performance when you're pushing an item :)

Collapse
 
dailydevtips1 profile image
Chris Bongers

I think in most cases the performance won't be exceeded when using it for everyday stuff most of the time I use it it's to push one item in an array smaller than 100, it doesn't really seem to affect things.

But valid point to keep in mind for bigger array

Collapse
 
lyrod profile image
Lyrod

NodeList to Array, you can use Array.from

const result = Array.from(document.querySelectorAll('div'))

// array

Collapse
 
dailydevtips1 profile image
Chris Bongers

Yes but then it wouldn't be a spread use haha.
We can do many of these using other methods.

Collapse
 
qq449245884 profile image
qq449245884

Dear Chris Bongers,may I translate your article into Chinese?I would like to share it with more developers in China. I will give the original author and original source.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Sure as long as you attribute the original that's fine with me 🤟

Collapse
 
kalashin1 profile image
Kinanee Samson

The spread operator is one of my favorites, nice post tho

Collapse
 
dailydevtips1 profile image
Chris Bongers

Thanks Kinanee, it's in my top 3 for sure ✌️

Collapse
 
crystalfp profile image
Mario Valle

In the first examples the equal sign disappeared.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Ah thanks! Missed that one! 🤟

Collapse
 
johannesbosch profile image
Johannes

Great summery!

Thanks!

Collapse
 
dailydevtips1 profile image
Chris Bongers

Thank you Johannes!