I have been working on a simple react project wherein I found this snippet
let hand1 =[]
let hand2 =[ ...this.props.pokemon];
while(hand1.length < hand2.length){
let randIdx = Math.floor(Math.random()*hand2.length);
let randPokemon = hand2.splice(randIdx,1)[0];
hand1.push(randPokemon)
}
What is the use of ..this.props.pokemon here?
In your case, it deep copy pokemon array from your props and prevent mutate the original array/object
Take a look at this example where spread syntax is not used:
const firstArray = [1, 2];
const secondArray = firstArray;
secondArray[0] = 9;
console.log(firstArray);
And here is when spread syntax is used
const firstArray = [1, 2];
const secondArray = [...firstArray];
secondArray[0] = 9;
console.log(firstArray);
let hand2 = [ ...this.props.pokemon]
The above expression takes all the values inside this.props.pokemon and puts it inside the hand2 array.
For eg:
const fruits = ['apple', 'banana']
const breakfast = [...fruits, 'milk']
console.log(breakfast) -> ['apple', 'banana', 'milk']
Whereas if you don't have the spread operator(...). It'll put the whole array there instead of just the values. For eg:
const fruits = ['apple', 'banana']
const breakfast = [fruits, 'milk']
console.log(breakfast) -> [['apple', 'banana'], 'milk']