javascriptwhile-loopinfinite-loopbreakdecrement

JavaScript 99Bottles - Infinite Loop


(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();


Solution

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