Basic Data Structures - Copy an Array with the Spread Operator

Tell us what’s happening:

Hi,
just wondering if there is an advantage of using this:

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // Only change code below this line
    newArr.push([...arr]);
    // Only change code above this line
    num--;
  }
  return newArr;
}

instead of

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // Only change code below this line
    newArr.push(arr);
    // Only change code above this line
    num--;
  }
  return newArr;

Your code so far

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // Only change code below this line
    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; rv:109.0) Gecko/20100101 Firefox/115.0

Challenge Information:

Basic Data Structures - Copy an Array with the Spread Operator

Hello, the thing their talking about is with an array name, right now arr is a param. I hope that helps.

Spreading the array into a new array creates a shallow copy. Pushing the array directly would mean you could mutate the original array through the copy (because it isn’t a copy).

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    newArr.push(arr);
    num--;
  }
  return newArr;
}

const originalArray = [true, false, true];
const newArray = copyMachine(originalArray, 1);
console.log(newArray); // [[true, false, true]]

newArray[0][0] = false;
// Original array has been changed
console.log(originalArray); // [ false, false, true ]

MDN: Copy an array

Ah ok, thanks for the explanation.
Appreciate your help!