Search code examples
javascriptwhile-loopweb-deployment

when i am putting the while loop inside a function why is the answer coming different?


var count = 99;
var word = "bottles";

 
    
   
   {
   
 
  
     while(count>0){
      if(count === 1){
       var word = "bottle";
                           }
         console.log( count + word +" beer on the wall, " + count + word + "  of beer. take one down and pass it around, " );
     count--;
       if(count>0){
      if(count === 1){
        var word = "bottle";
                           }
     console.log( count + word + " beer on the wall.");
                        }
 else{
  if(count<1){
   var word = "bottles";
                   }
  console.log("no more " + word + " of beer on the wall.");
     }
    }
  }

and when i am putting it inside a function the result changes.

var count = 99;
var word = "bottles";

 
    
   
  function myName() {
   
 
  
     while(count>0){
      if(count === 1){
       var word = "bottle";
                           }
         console.log( count + word +" beer on the wall, " + count + word + "  of beer. take one down and pass it around, " );
     count--;
       if(count>0){
      if(count === 1){
        var word = "bottle";
                           }
     console.log( count + word + " beer on the wall.");
                        }
 else{
  if(count<1){
   var word = "bottles";
                   }
  console.log("no more " + word + " of beer on the wall.");
     }
    }
  }
  myName();

can anybody please tell me what is going wrong with putting function against the while loop. you can run the code in the snippet and see the difference of results. also the code looks a lot untidy can anyone suggest me ways to reduce the lines.


Solution

  • the issue come from the declaration of another word variable inside if

    if(count === 1){
        var word = "bottle";
    }
    

    when you do this you declare a word variable only available in the if bracket

    an idea to enhance your code is to have the two word bottle and bottles inside variables and calculate a true word at begining of while iteration

        var finalWord = (count === 1) ? word : words;
    

    var count = 99;
    var words = "bottles";
    var word = "bottle";
    
    function myName() {
    
      while (count > 0) {
        var finalWord = (count === 1) ? word : words;
        console.log(count + finalWord + " beer on the wall, " + count + finalWord + "  of beer. take one down and pass it around, ");
        count--;
        if (count > 0) {
          console.log(count + finalWord + " beer on the wall.");
        } else {
          console.log("no more " + finalWord + " of beer on the wall.");
        }
      }
    }
    myName();