Copy machine with [...this]

Tell us what’s happening:
Describe your issue in detail here.

I was able to somehow figure out how to prevent reinitialization issue here but I don’t get why newArr is reinitialized with every new iteration. Could you explain that please?
Your code so far


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

Challenge: Copy an Array with the Spread Operator

Link to the challenge:

I don’t think it is. You are initializing it on the very first line of the function body and then pushing an array into it on every iteration of the while loop. But pushing an array into newArr is not re-initializing it. But perhaps I am not understanding your question correctly?

Hint 2 says if the code was this:

while (num >= 1) {
    newArr = [...arr]
    num--;
}

it would reinitialise newArr with every new iteration of the while loop. I was trying to ask why that was happening.

Ahh, I see what you are referring to now. I think that hint 2 is just demonstrating how the spread operator works. I don’t think it is suggesting that you should use that exact code in your solution. I agree, it is slightly confusing that the hint uses the newArr variable, which is what the challenge uses as well. But the hint does tell you that

“The code above will copy all of the elements into newArr but will also reinitialise newArr with every new iteration of the while loop.”

I think this is actually warning you that the code in the hint will reinitialise newArr. In other words, you don’t want to use this code asis because it will reinitialise the variable, something you don’t want to do. And the bullet point below explains what you should do instead.

Should the hint use the same variable name as the challenge? Perhaps not to avoid confusion. But if you understand all of the bullet points in the hint then I think it shouldn’t matter.

1 Like

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