Search code examples
javascriptarraysfor-loopnested-loops

How iterating through an empty array works?


The task:

So I have this task, to create a lottery game. The restrictions are:

  • Needs to be 5 numbers
  • From 1-90
  • Can't have duplicates

My problem:

I don't understand how iterating through an empty array works in theory. According to my understanding, this function contains the following:

  • Creates an empty array, so the lottery numbers can be stored here, after they're checked for duplicates.
  • There is a for loop and a nested for loop. Here is what I don't understand.
  • i = 0. As 0 is indeed less than 5 it executes the following. Generates a number between 1-90 (let's say 22), and a variable which value is false. Now, the nested for loop needs to run as long as j is less then array.length.
  • First question: The array is empty now, without any value pushed into it. How can the for loop work, if it has no length yet?
  • Second question: The if statement states, that if the randomNum (now 22) is the same as the array[j] (assuming now it's also 22) isDuplicated = true. How can I compare a number to an empty array, if it has no values pushed into it? I don't understand the proccess.

Summary:

  • The code works. This was an assignment last week. I couldn't figure it out due to lack of understanding in nested loops, arrays etc. I've searched around google yesterday, but I only find solutions, not explanations. Any source, posts, articles on this is much appreciated. Code is below, thank you!

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;


Solution

  • 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.