How to use JavaScript's spread syntax
August 2, 2018
Think of an array like a deck of cards. You can spread the cards out, then you have a bunch of individual cards. JavaScript's spread (...
) syntax works the same way. The spread syntax literally spreads an array into its individual values:
const a = [1, 2, 3, 4, 5]
const b = [...a, 6]
console.log(b) // [1, 2, 3, 4, 5, 6]
Want another example? Let's say you have a function that accepts three arguments, and you have an array of the arguments you want to use:
const words = ['He', 'plays', 'Zelda']
function logThreeWords(a, b, c) {
console.log(a, b, c)
}
You could call logThreeWords
like this:
logThreeWords(words[0], words[1], words[2]) // He plays Zelda
Or you could just use the spread operator:
logThreeWords(...words) // He plays Zelda
Bonus: using spread while destructuring
The fun doesn't stop at arrays. You can also use it for destructuring:
const { name, ...rest } = {
name: 'Link',
hair: 'Blonde',
weapon: 'Master Sword'
}
console.log(name) // Link
console.log(rest) // { hair: 'blonde', weapon: 'Master Sword' }
console.log(rest.weapon) // Master Sword
As you can see, the spread syntax is simply saving you from having to type out data explicitly. It takes the rest of an object and packs it into a variable for you.