The task:
So I have this task, to create a lottery game. The restrictions are:
My problem:
I don't understand how iterating through an empty array works in theory. According to my understanding, this function contains the following:
Summary:
function LotteryGenerator() {
array = [];
for (let i = 0; i < 5; i++) {
let randomNum = Math.round(Math.random() * 89) + 1;
let isDuplicated = false;
for (let j = 0; j < array.length; j++) {
if (randomNum == array[j]) {
isDuplicated = true;
}
}
if (isDuplicated == false) {
array.push(randomNum);
}
else {
i--;
}
}
return array;
On the first iteration, the outer loop starts and gets to the nested loop. At the nested loop, which is just a duplicate finder, the condition isn’t met (j < array.length) so the loop doesn’t get executed.
Code continues past the nested loop and adds the first item to the array.
Second iteration, we arrive back to that nested loop, and now the array.length = 1, so the nested loop runs one time. And this continues. On the 5th iteration of the outer loop, the nested loop will iterate 5 times before moving on to push the new random number to the array.
So in summary the first iteration it doesn’t matter that the nested loop doesn’t run because there’s no chance of a duplicate.