Basic Data Structures - Copy an Array with the Spread Operator

Tell us what’s happening:

Describe your issue in detail here.
I don’t understand the point of copying arrays with spread operator.
To my mind, if I wanted to have another copy of my variable, I could just assign old one to new one and it will be copy of previous one. For this test newArr.push(arr); can do the work as well as newArr.push([…arr]); What is the difference ?

Your code so far

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // Only change code below this line
   //  newArr.push(arr); this can also do the same as the line below without spread  

  
  newArr.push([...arr]); 
    // Only change code above this line
    num--;
  }
  return newArr;
}

console.log(copyMachine([true, false, true], 2));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36

Challenge Information:

Basic Data Structures - Copy an Array with the Spread Operator

Try it and see.

  1. create an array and assign it to the variable originalArray

  2. assign the contents of originalArray to a new variable, copyArray

  3. try copyArray.push(42)

  4. then look at the contents of copyArray and originalArray

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.