What is the spread operator?
The spread operator - it looks like this: ...
- has three purposes it can serve. Let's quickly break them down!
Arrays
One way the spread operator can be used is to copy an array into another array. Here's an example:
const heroes = ['Westley', 'Buttercup', 'Inigo', 'Fezzik']
const villains = ['Humperdinck', 'Rugen', 'Vizzini']
const characters = ['Miracle Max', 'The Albino', ...heroes, ...villains]
console.log(characters)
// ['Miracle Max', 'The Albino', 'Westley', 'Buttercup', 'Inigo', 'Fezzik', 'Humperdinck', 'Rugen', 'Vizzini']
Order matters! You can imagine all the elements being placed (or spread) into the spot that you spread them in the array.
const characters = ['Miracle Max', ...villains, ...heroes, 'The Albino']
console.log(characters)
// ['Miracle Max', 'Humperdinck', 'Rugen', 'Vizzini', 'Westley', 'Buttercup', 'Inigo', 'Fezzik', 'The Albino']
It's also important to remember that this is a shallow operation. Any objects or arrays that are elements of the array being spread will not themselves be copied. You'll need something like lodash's cloneDeep
function for that.
const companions = [['Westley', 'Buttercup'], ['Inigo', 'Fezzik'], ['Humperdinck', 'Rugen']]
const companionsCopy = [...companions]
companionsCopy[2].push('Yellin')
console.log(companions[2])
// ['Humperdinck', 'Rugen', 'Yellin']
Objects
The spread operator can be used in the same way with objects!
const character = { name: 'Westley', aliases: ['The Man in Black', 'The Dread Pirate Roberts', 'Farm Boy'] }
const stats = { strength: 17, dexterity: 20, intelligence: 22, charisma: 18, luck: 2 }
const sheet = { ...character, ...sheet }
console.log(sheet)
// {
// name: 'Westley',
// aliases: ['The Man in Black', 'The Dread Pirate Roberts', 'Farm Boy'],
// strength: 17,
// dexterity: 20,
// intelligence: 22,
// charisma: 18,
// luck: 2
// }
Function Arguments
The last usage is perhaps the most uncommon. You can use the spread operator to pass array elements in as arguments to a function.
const inigo = ['Inigo Montoya', 'killed my father', 'die']
const hello = (name, statement, action) => `Hello. My name is ${name}. You ${statement}. Prepare to ${action}.`
hello(...inigo)
// 'Hello. My name is Inigo Montoya. You killed my father. Prepare to die.'
It's rare that you will find this useful, but there are circumstances in which it can be very helpful. For example, some functions take a variable number of arguments. Lodash's intersection
function is one such example! It takes an arbitrary number of arrays as arguments and returns an array which contains only the elements that are present in all the provided arrays.
const arr = [1, 2, 3]
const add = [5, 6, 7]
const result = _.concat(arr, 4, ...add)
console.log(result)
// [1, 2, 3, 4, 5, 6, 7]
Conclusion
The spread operator is a very useful tool when used well. I hope you found this quick overview helpful! Thanks for reading!