ES6: spread operator

The spread guy allows us to extract/expand data from an array make our lives 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 a JS Bin with the examples.

More posts