Copy an Array with the Spread Operator...arr

This worked for me newArr.push([…arr]); but still don’t know how


My function looks like that and it is works:

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


This code is pushing arr into newArr.
It’s like putting one piece of fruit into a basket.
Every time you run this line, a new piece of fruit is put into the basket.


I initially tried: newArr.push(…arr);
It returned one array with arr’s numbers spread num amount of times.
Your method, in contrast, created num amount of arrays with arr spreaded in each one.

Thanks, I was confused until I saw your solution: newArr.push([…arr]);
and worked it out.

This work perfectly for me. So , newArr will get the whole array and will repeat it will the number comes to zero. Awesome

1 Like

4 posts were split to a new topic: Copy machine code not working

newArr is being overridden every time. You can simply do
newArr[num-1] = […arr];
This will ensure the whole arr will get copied num times to newArr

So the solution is shown above several times. What I’d like to know is what benefit newArr.push([...arr]); has over simply using newArr.push(arr);.

The difference is […arr] is a new array containing a copy of arr which is the entire point. If you write newArr.push(arr) then you are just inserting the reference to the original arr into newArr multiple times. It may appear they are the same, but they are very different. I have created the following which demonstrates the real difference of the two methods. Run the code and see what is displayed in the console.


Thanks for you example Randell,

I couldn’t pass this exercise because I was using newArr.push(arr) so I made a workaround to pass it.

let pass = [...arg];

Now I see clearly the difference, why I should use ([…arg]) instead of (arr)

By the way, I think there is a mistake in your example in line 42 it should be copiesHolder2 instead of copiesHolder.


Yes, that was a typo. Good catch! I have fixed it now.

newArr[newArr.length] = […arr];

Hello guys. I’ve manage to pass the test but I’m not sure if my solution is also correct. Here it is:

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

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

Do u know why newArr[num] = […arr]; the result is “,true,false,true,true,false,true”, why we have the first comma?

Because in that way newArr[0] stay empty

why newArr[num - 1] = […arr]; it is not empty?

Follow what num does, and you will see in one case you get a 0 as lowest number in the brackets and in the other case you get a 1

1 Like

sorry can not get it , is not that example using same method ?!

Which example? I am not understanding your question.