Help understanding "num--" at the end of a function

" We have defined a function, copyMachine which takes arr (an array) and num (a number) as arguments. The function is supposed to return a new array made up of num copies of arr . We have done most of the work for you, but it doesn’t work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!)."

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 actually have two questions that I’m trying to understand:
while (num >= 1) ------- why do we need this?
num–; why do we need this?

I hope I’ve made myself clear.
Regards!

In order to answer you and have it mean something to you, first you must answer this:

What does this function do ? Or if you don’t know, tell me what does this exercise want this function to do?

while(num >= 1){//code here} is a type of loop. How would you expect this code to run x number of times without one? And num--; is there because you need something to stop that loop, otherwise it would just keep running forever. So num-- is taking the number passed to the function and decreasing it by one each time the while loop runs, eventually making the condition in the while loop false and stopping the loop.

1 Like

Thanks a lot! I get it now.

All the best!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.