Copy an Array with the Spread Operator Why wouldn't this work?

Tell us what’s happening:
I understand the solution that they gave by using an obj = [arr] first, but why doesn’t my solution also work? When I use the log.console to test all the tests it gave in the exercise, the console returned all correct answers… head-scratch

Your code so far


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

// change code here to test different cases:
console.log(copyMachine([1, 2, 3], 5));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator

But arr is already defined as an array, no? So shouldn’t ...arr pass the whole array object into the newArr?

Well, if arr was [1, 2, 3] then it would be the same as newArr.push(1, 2, 3) which would push three items onto the array. But it is supposed to push an array of three items onto the array.

Ok. I think I get it. Wow what a subtle difference! Thank you!

1 Like