The problem with newArr = newArr.push([...arr])
is because the push()
method doensn’t actually return an array—it’s return value is the length of the array, so assigning the result to newArr
the first time is assigning the value 1
to newArr.
It is worth noting that the instructions are (I think) deliberately vague in order to avoid giving you the answer (but I personally think that it’s unnecessarily vague).
The whole point of copying an array is that you won’t mutate it if you perform mutating operations, like push
on its copy. For example, consider this:
let arr = [1, 2, 3];
let brr = arr;
arr.unshift(0);
arr; // [0, 1, 2, 3]
brr; // [0, 1, 2, 3]
let arr = [1, 2, 3];
let brr = arr.slice();
arr.unshift(0);
arr; // [0, 1, 2, 3]
brr; // [1, 2, 3]
And the ...
spread operator also lets you copy the whole array:
let arr = [1, 2, 3];
let brr = [...arr];
arr.unshift(0);
arr; // [0, 1, 2, 3]
brr; // [1, 2, 3]
But there is more to the spread operator, consider this example:
let arr = [0, 1, 2];
let brr = [3, 4];
let crr = [...arr, ...brr];
let drr = [...brr, ...arr];
arr; // [0, 1, 2]
brr; // [3, 4]
crr; // [0, 1, 2, 3, 4]
drr; // [3, 4, 0, 1, 2]
In the example above, you are decomposing the elements of the array, and putting them back in order. And the thing to note here is that push()
is not necessary in this case. The whole point of this spread operator exercise is that you can use something that syntactically simpler to achieve the same result as push.
Since you have also just posted your solution (please blur it), it is worth noting that there is a solution that involves only the spread operator and doesn’t require push
.
I hope that helps!