Please help copy array of spread operator

Hi, I’m not sure what to do here. Likely due to my lack of understanding with reinitializing according to the hint. Please assume I don’t know anything about how to do initializing when helping me on this one.


Your code so far

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

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

// The function is supposed to return a new array made up of num copies of arr.
// Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36.

Challenge: Copy an Array with the Spread Operator

Link to the challenge:

Your function takes in 2 parameters: “arr” and “num”.

Your task is to modify the given function in a way, so that the result is an array, that includes “arr”, a total of “num” times.

The function returns newArr, which is initialized as an empty array at the start of the function.

So using the spread operator, you want to add “arr” to “newArr” within the while loop.

You seem to have the spread operator correct, but you don’t have to/shouldn’t define newArr again. You just want to add “arr” to it.

Now how do you add something to an array? :wink:

1 Like

Thanks. I got it! For some reason “The function is supposed to return a new array made up of num copies of arr” wasn’t clicking in my head.

Just curious, is there ever a situation when you want to return something and don’t need to initialize a variable in the beginning? May seem like a weird question but I’m not 100% on initializing and reinitializing

I guess it depends on the circumstances.
Of the top of my head I can’t really think of an example, where one might not need initialization. Except for maybe in simple cases, like for example a function that returns the sum of a and b, where you could just return a+b. but even here you could do it like this:

function addNumbers(a, b) {
    let solution = a + b
    return solution

I feel like this adds a bit of clarity.

So just keep the spirit up, and eventually it will become really intuitive.
Perhaps that’s also why I am not sure that I can answer your question clearly.
Most of the time i just initialize variables when I feel like I need one.

1 Like