0

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?

  • 2
    Do you mean about [Spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)? – Ryan Le Sep 09 '21 at 02:42
  • It uses the [`spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) to create a copy of the array so you don't mutate the one in props. – Andy Sep 09 '21 at 02:43

2 Answers2

0

It is Spread syntax (...)

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);
Ryan Le
  • 7,708
  • 1
  • 13
  • 23
0
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']
nexter21
  • 11
  • 1