The spread operator a.ka. the three magic dots expand an iterable in place. An iterable can be an array, a string, or a set.
The spread operator is used in three main cases which are in a function call when making an array literal and making an object literal.
Imagine you want to find the maximum number in an array.
const randomArray=[5,4,8,200,-4]
Before the spread operator syntax feature was added to javascript-prior to ES6-we would use something like :
Math.max.apply(null, randomArray)
However, there is a better way which is Math.max(...randomArray).
This works because the spread operator sort of unpacks the array elements and passes them to the max
method one by one.
Another use case of the operator is when merging or joining arrays. And if you do the following
const fullTimeEmployees = ["Dave", "Anna", "John"];const partTimeEmployees = ["Samantha", "Peter", "Donald"];const allEmployees = [fullTimeEmployees, partTimeEmployees];console.log(allEmployees);
You will end up with a nested array
[[ ‘Dave’, ‘Anna’, ‘John’ ], [ ‘Samantha’, ‘Peter’, ‘Donald’ ]]
So, we can use one of the easiest methods of joining arrays which is …you guessed it the spread operator like so.
console.log([...fullTimeEmployees, ...partTimeEmployees]);
And the result is as expected
[‘Dave’, ‘Anna’, ‘John’, ‘Samantha’, ‘Peter’, ‘Donald’ ]
I know we can achieve the same thing by using the concat
method const allEmployees = fullTimeEmployees.concat(partTimeEmployees);
Incidentally, we can also break a string into its component characters using the spread operator like so:
const spreadableString=”This is awesome”
[...spreadableString]
will give us
[
‘T’, ‘h’, ‘i’, ‘s’,
‘ ‘, ‘i’, ‘s’, ‘ ‘,
‘a’, ‘w’, ‘e’, ‘s’,
‘o’, ‘m’, ‘e’
]
This is no surprise as strings are also iterables.
One of the common issues when copying an array because we want to work on it without affecting the original array is that when one of the arrays changes the other one gets affected too. Here is an example
let languagesInChina = ["Mandarin", "Cantonese"];let copyOflanguagesInChina = languagesInChina;copyOflanguagesInChina.push("Hunanese");console.log(languagesInChina);
Because both languagesInChina
and copyOflanguagesInChina
reference the same object they will both contain the updated version with three languages.
['Mandarin', 'Cantonese', 'Hunanese' ]
But the spread operator comes to the rescue and all we have to do is
let copyOflanguagesInChina = [...languagesInChina];
Now our original array stays unaffected — phew that was close.
Note: This use case of the operator is quite useful, a case in point would be when working with React states. Because we don’t want to mutate the state copying it like above is one of the best ways.
Remember though, the spread operator isn’t suitable for copying multidimensional arrays.
Another use case would be to change a Nodelist which is array-like object into a bonafide array that uses methods such as map()
and filter()
.
Say we want to change the third image’s src
attribute on the fly. Here is what we do:
const imgEls = [...document.querySelectorAll("img")];
const thirdImage = imgEls.map((anImage, i) => {if (i === 2) {anImage.setAttribute("src","https://images.unsplash.com/photo-1601327391865-398708fcb4ba?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTV8fHNwcmVhZCUyMHdpbmdzfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=60");}})console.log(thirdImage);
So, our third image is now non-empty. See below for the screenshot of the developer console.
This example is a bit contrived but I hope it illustrates the use case well.
The last use case is something I came across while I was doing this React recipe project where I’d need to pass the values of an object as props. You can imagine how painful it is doing something like
return <Recipe key={recipe.id} id={recipe.id} name={recipe.name}
servings={recipe.servings}
cookTime = { recipe.cookTime }
instructions={recipe.instructions}/>
Instead, do this and you are all sorted
return <Recipe key={recipe.id} {...recipe} />
In my opinion, the spread operator is something once you start using it you wonder how there was a time it didn’t exist. I commiserate developers before 2015.
Thanks for reading and please feel free to comment and follow me for more articles on tech topics.