Copy an Array with a Spread operator

Tell us what’s happening:

Need help/clarification. Any idea why the below code doesn’t work?

Your code so far


function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
  // Only change code below this line
newArr = 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/85.0.4183.83 Safari/537.36.

Challenge: Copy an Array with the Spread Operator

Link to the challenge:

Hello!

The problem is that Array.prototype.push returns the new array length, not the actual/modified array. This means that you’re overwriting the newArr with the actual length of it the first time. The following iterations should fail with an error:

TypeError: newArr.push is not a function

Be sure to always check the documentation of the method/function you’re attempting to use :slight_smile:.

Hope it helps!

2 Likes

Oh. By assigning newArr = newArr.push, I am essentially setting its value to the length of the array and not the values. Understood.

Thank you very much.

1 Like