Day 29: Mopping up Lesson 4: Spread Operator If you have an array or object that you want to split apart you can use the spread operator ...
. There are a few places to use this but most common is spreading one array into another.
HTML JS
const arrayOne = [ 35 , 55 , 40 , 50 , 50 , 90 ] ;
const arrayTwo = [ 40 , 33 , 12 , 90 , 53 , 37 ] ;
const newArray = [ ... arrayOne , ... arrayTwo ] ;
console . log ( newArray ) ;
Likewise for spreading an object into another.
HTML JS
const pokemon = { name : "Pikachu" , hp : 35 } ;
const stats = { attack : 55 , defense : 40 , specialA : 50 , specialD : 50 , speed : 90 } ;
const fullPokemon = { ... pokemon , ... stats } ;
console . log ( fullPokemon )
You can also use spread along with destructuring.
In the previous destructuring object example you might want to destructure two properties and then spread the rest.
HTML JS
const pokemon = { name : "Pikachu" , hp : 35 , attack : 55 , defense : 40 , specialA : 50 , specialD : 50 , speed : 90 } ;
const { name , speed , ... rest } = pokemon ;
const description = ` ${ name } is a pokemon with ${ speed } speed ` ;
console . log ( description ) ;
console . log ( rest ) ;
You can see that rest
contains the rest of the object properties.
Likewise you can do the same with arrays.
HTML JS
const pokemon = [ 35 , 55 , 40 , 50 , 50 , 90 ] ;
const [ hp , attack , ... rest ] = pokemon ;
const question = ` Which Pokemon has ${ hp } health and ${ attack } attack? ` ;
console . log ( question ) ;
console . log ( rest ) ;
The spread operator is sometimes call the rest operator