Copy an Array with the Spread Operator

Hi guys o/
The following code (into the While condicion)

newArr.push(arr);

generates the same output. Was it wrong?

can you give some more context to your question? (such as a link to the challenge description)

The challenge is asking for a shallow copy of the array.

If you push the array without using spread you are pushing a reference to the array, not a copy.

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

const originalArray = [true, false, true];
const copy = copyMachine(originalArray, 1);

console.log(copy); // [[true, false, true]]
copy[0][0] = false;
console.log(copy); // [[false, false, true]]

// originalArray was mutated
console.log(originalArray); // [[false, false, true]]

If you use [...arr] with .push() then originalArray will not be mutated.


1 Like

uooou! nice! thank you so much!