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];
- Copy an array
- Combine arrays
- Add an item to an array
- Adding a property to an object
- Use Math() functions
- Spread array as function arguments
- Pass unlimited arguments to a function
- Converting a nodeList into an array
- Destructuring an object
- Exploding a string
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 ]
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.
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 ]
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];
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];
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' ]
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' ]
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'
};
To add the age to this user object, we can again leverage the spread operator.
const output = {...user, age: 31};
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 }
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];
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
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
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
This will return NaN
because JavaScript doesn't know what to max on an array.
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);
}
We could call this function in the following manner:
myFunc(1, 2, 3);
But what happens if we have an array that we want to pass.
const arr1 = [1, 2, 3];
We can now use the spread operator to spread this array into our function.
myFunc(...arr1);
// 1
// 2
// 3
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
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);
};
If we now call this function with multiple arguments we see the following happening.
myFunc(1, 'a', new Date());
It will return the following:
[
1,
'a',
Date {
__proto__: Date {}
}
]
We are then able to dynamically loop over the arguments.
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]
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>
Note: If you want to learn more about looping over nodeList results check out this article.
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
};
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 }
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.
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';
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' ]
There you go, an array of letters.
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