ampersandwitch
ampersandwitch

Reputation: 23

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

Upvotes: 2

Views: 467

Answers (4)

Godspower Thompson
Godspower Thompson

Reputation: 1

*let x = 99
let y = x - 1
function beer() {
    while (x > 1) {
        x--
        y--
        console.log(x + " bottles of bear on the wall, " + x + " bottles of bear. Take one down and pass it around, " + y + " bottles of bear on the wall.")
    }
}*

Upvotes: 0

iAmOren
iAmOren

Reputation: 2804

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

Upvotes: 2

Alekos Dordas
Alekos Dordas

Reputation: 810

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.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49896

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

Upvotes: 4

Related Questions