Copy an Array with the Spread Operator

Tell us what’s happening:

What’s the difference between ‘newArr = newArr.push([…arr]);’ and ‘newArr.push([…arr]);’ ?
Why the first one does not work?

Your code so far


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

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 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

From MDN - Push

The push() method adds one or more elements to the end of an array and returns the new length of the array.

If you check the first example visible in the above linked page you’ll see push method return the total length of the array: this is the value you’re assigning to newArr with your first try^^

1 Like