Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why i am not able to see output for 100 times in the javascript console even if i am successfully looping through 100 times and printing console.log?

enter image description hereThis is my output image:

function bottles_of_beer(){
        var i=99;
        while(i>=0){
        if(i==1){
            console.log(i+" bottles of beer on the wall, "+i+" bottles of beer.\nTake one down and pass it around, No more bottles of beer on the wall.");
        }
        else if(i==0){
            console.log("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.");
        }
        else{
            console.log(i+" bottles of beer on the wall, "+i+" bottles of beer.\nTake one down and pass it around, "+i-1+" bottles of beer on the wall.")
        }
        i--;
    }
    }

I was expecting the output printed in the console 100 times. But it is just printing the output for i=1 and i=0 and for i : 99 to 2 it is just printing one output. Why is this happening can anybody please explain? and how can i display/print the output 100 times in the console?

This is the output i am getting when i call "bottles_of_beer()":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

98 NaN bottles of beer on the wall.

1 bottles of beer on the wall, 1 bottles of beer.
Take one down and pass it around, No more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

>Solution :

In your last console log:

console.log(
    i +
      " bottles of beer on the wall, " +
      i +
      " bottles of beer.\nTake one down and pass it around, " +
      i -
      1 +
      " bottles of beer on the wall."
  );

Everything before the -1 is fine as a string, but when you have some_string - 1 JS tries to convert the string to a number then subtract 1. That’s why youre getting NaN.

To solve it just wrap your i - 1 in the last console log in some brackets

console.log(
    i +
      " bottles of beer on the wall, " +
      i +
      " bottles of beer.\nTake one down and pass it around, " +
      (i - 1) +
      " bottles of beer on the wall."
  );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading