1

I'm learning JavaScript with the help of a number of books. In one of them I came up with a script that displays a couple of flags and then you click on them to randomly change them:

var myImages = new Array("usa.gif","canada.gif","jamaica.gif","mexico.gif");

function changeImg(that) {
        var newImgNumber = Math.round(Math.random() * 3);

        while (that.src.indexOf(myImages[newImgNumber]) != -1)
        {
            newImgNumber = Math.round(Math.random() * 3);
        }

        that.src = myImages[newImgNumber];
        return false;
}

It has a while loop to make sure that when you click on a flag you don't end up with the same one. The rest of the code in HTML looks like this:

<body>
    <img name="img0" src="usa.gif" border="0" onclick="return changeImg(this)" />
    <img name="img1" src="mexico.gif" border="0" onclick="return changeImg(this)" />
</body>

Now, my question is, if I use an IF statement instead of a while loop, apparently the code works the same. In this particular example why is the while loop used instead of IF? Thanks.

rohn
  • 77
  • 1
  • 5

4 Answers4

6

The while statement basically translates as "while the number I've chosen matches the index of the image already in the current image tag, continue". So while an if statement may work most of the time, it's possible that your random number generator could generate, say, the number 0 multiple times in a row when you click on img0. while ensures that eventually you'll get a new image.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
3

There's a random number involved; you could get the same random number twice in a row.

Checking once is insufficient–the next number generated could be the same.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1

No because you could choose the same one twice in a row since you are using random numbers.

Wowsk
  • 3,637
  • 2
  • 18
  • 29
1

Your goal is to make a random shuffle. Try to read answers to that question: How to randomize (shuffle) a JavaScript array?

Community
  • 1
  • 1
Schullz
  • 283
  • 1
  • 6
  • 18
  • OP's goal was to understand the JS code in the book, I think? – Dave Newton Sep 24 '15 at 19:45
  • Yes, thank you. Evidently I'm new at coding and I'm just trying to understand the logic behind the statements by asking "what if i used this instead of that". – rohn Sep 24 '15 at 20:32