JavaScript 99Bottles - Infinite Loop

Viewed 150

(I already know that this isn't the most elegant solution to the 99 bottles code challenge, but I'd really like to know how not to repeat this mistake in the future.)

When this runs in the console it repeats the (count === 0) condition and repeats nothing but the "0 bottles of beer" console log until it crashes.

I've experimented with using a 'break' statement after the count decrements to 0, but haven't had any success.

let count = 99;

function bottlesOfBeer() {
    while (count >= 0) {
        if (count > 0) {
            console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
            count--;
            console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");  
        };

        if (count === 0) {
            console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
        } //*this is where I tried the break statement*
    }
};

bottlesOfBeer();

3 Answers

You only decrement count when it is above 0, so it never goes below 0; but the loop continues as long as count >= 0.

Here's the corrected code:

function bottlesOfBeer() {
  var count = 99;
  while (count > 0) {
    console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
    count--;
    console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");  
  }
  console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
};

bottlesOfBeer();

Please read and understand - and ask, if you have questions.
In the code, count was set to 99.
The while loop stops when count gets to zero.
When the loop exists, count IS zero, and the appropriate line of the song is logged.
I've removed blank lines...
Other than that - your code is pretty neat: no weird indentations (you wouldn't believe what I see - not that it would effect execution, just easier to read).

Turn while (count >= 0) into while (count > 0) and you are good to go!

The problem is that when it reaches zero you just log the message without decreasing it any more, so it stays zero and (count >= 0) is always true.

Related