The spread guy allow us extract/expand data from an array make our lifes easier. Confused? I guess I could not explain. Go to practice. Imagine the following arrays:
let mortalKombat = ['Scorpion', 'Sub Zero', 'Liu Kang'];
let newCharacters = ['Reptile', 'Kitana'];
If we had to add the new fighters to the main array, we could try something like that:
mortalKombat.push(newCharacters);
console.log(mortalKombat);
// ['Scorpion', 'Sub Zero', 'Liu Kang', ['Reptile', 'Kitana']]
The data is there, but not in the way that we want. So we need to manipulate it before:
newCharacters.forEach(function(fighter) {
mortalKombat.push(fighter);
});
console.log(mortalKombat);
// ['Scorpion', 'Sub Zero', 'Liu Kang', 'Reptile', 'Kitana']
The operator spread arrives making magic and leaving everything beautiful.
mortalKombat.push(...newCharacters);
console.log(mortalKombat);
// ['Scorpion', 'Sub Zero', 'Liu Kang', 'Reptile', 'Kitana']
Here you can find an JS Bin with the examples.
Do you like it? Did I write something stupid? Do you want to improve? Open an issue mentioning the post and let’s talk about it.