No output for (num > 1)

Tell us what’s happening:
Everything works okay or almost, except it’s not returning output for num > 1.

The browser is seeing the code as a potential infinite loop on line 3.

Your code so far


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

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36.

Challenge: Copy an Array with the Spread Operator

Link to the challenge:

Hello and welcome to the forum!

It looks like you created an infinite loop! num never changes, so you will keep looping forever.

@JeremyLT num-- ?

@therepositor The problem is you are overwriting newArr at each loop iteration. Check the hint page, you don’t have to look at the solution but it gives you a bit of help anyway.

Woops, good catch. Ignore my post. Time to stop coding for today.

i had to use push(). it’s working now.

Thanks.

another possible answer:

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

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

Hi and welcome to the forum.

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

In general, it’s best to not post only for the sake of sharing solutions.

Thank you.

3 Likes