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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mortalKombat.push(...newCharacters); | |
console.log(mortalKombat); | |
// ['Scorpion', 'Sub Zero', 'Liu Kang', 'Reptile', 'Kitana'] |
Here you can find a JS Bin with the examples.