Difference between calling an array with and without a spread operatior

In the “Basic Data Structures: Copy an Array with the Spread Operator” we have to push the array with the spread operator.

One of the requirements for this exercise is: copyMachine([true, false, true], 2) should return [[true, false, true], [true, false, true]]

When I use newArr.push(arr), the fcc console returns [ [ true, false, true ], [ true, false, true ] ], when I use the spread operator newArr.push(...arr), the fcc console returns [ true, false, true, true, false, true ] but the exercise is counted as correct.

So although there’s a difference between the two I don’t exactly get what it is and why would we need to use the spread operator instead of just calling the whole array.

Hello there,

Could you please provide your whole code?

It’s more of a general question rather than an exercise-specific one (I’ve solved it). But here’s the exercise I’m talking about:

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

console.log(copyMachine([true, false, true], 2));

I’m interested in knowing the difference between using arr and ...arr.

Also the first time I did the exercise, using newArr.push(...arr) marked the exercise as correct but this time it was incorrect and I had to write ([...arr]) to be counted as correct.

... spreads the values of an iterable thing (an array or a string or a map or a set). So it’s as if it gives you the values of them one by one.


So [...arr] is saying “take the values in arr, and put them into a new array”.

If arr is [1,2,3], then [...arr] is taking the values 1, 2 and 3 and putting them into a new array: that new array is [1,2,3], but it isn’t the same array, it’s a copy.

On the other hand, newArr.push(...arr) is saying “take the values in arr, and put them into that function as arguments”.

If arr is [1,2,3], then newArr.push(...arr) is taking the values 1, 2 and 3 and putting them into that function, it resolves to newArr.push(1,2,3)


If we use that example, with arr being [1,2,3]:

newArr.push(...arr) is the same as newArr.push(1,2,3), and means newArr is now [1,2,3], you are pushing values into newArr

newArr.push([...arr]) is the same as newArr.push([1,2,3]), and means newArr is now [[1,2,3]], you are pushing an array into newArr

The task asks you to push n number of copies of the array arr into the the array newArr, so the latter is what you want

1 Like

Perhaps to add to @DanCouper’s answer above, the spread syntax makes a shallow copy of the array. If you are dealing with deeply nested arrays, some of the elements of the clone will retain reference to elements of the parent array. I recently wasted an entire weekend debugging a bug caused by making shallow copy of an array of objects using spread syntax.

1 Like