Home > Net >  Why i am not able to see output for 100 times in the javascript console even if i am successfully lo
Why i am not able to see output for 100 times in the javascript console even if i am successfully lo

Time:06-28

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()":

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.

CodePudding user response:

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

CodePudding user response:

There are two ways from which u can solve this
1.You can place , instead of before i-1

 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."
  );
}

2.You can wrap in brackets

(i-1)
  • Related