Trouble with my loop; it never ends


#1



https://www.codecademy.com/courses/javascript-beginner-en-Bthev-mskY8/1/4?curriculum_id=506324b3a7dffd00020bf661


I don't receive any error messages but my loop never ends. It keeps prompting and posting results even though I feel the while loop requirements are eventually met. What am I doing wrong here?


var game = 0;
do {
    var userChoice = prompt("Best two out of three. Do you choose rock, paper or scissors?");
    var computerChoice = Math.random();
    if (computerChoice < 0.34) {
    	computerChoice = "rock";
    } else if(computerChoice <= 0.67) {
    	computerChoice = "paper";
    } else {
    	computerChoice = "scissors";
    } console.log("Computer: " + computerChoice);
    
    var compare = function ( choice1 , choice2 ) {
        if ( choice1 === choice2 ) {
            return ( "The result is a tie!" );
        }
        else if ( choice1.toLowerCase() === "rock" ) {
            if ( choice2 === "scissors" ) {
              return ( "rock wins" );
              game += 1;
            }
            else {
                return ( "paper wins" );
                game -= 1;
            }
        }
        else if ( choice1.toLowerCase() === "paper" ) {
            if ( choice2 === "rock" ) {
                return ( "paper wins" );
                game += 1;
            }
            else {
                return ( "scissors wins" );
                game -= 1;
            }
        }
        else if ( choice1.toLowerCase() === "scissors" ) {
            if ( choice2 === "rock" ) {
                return ( "rock wins" );
                game -= 1;
            }
            else {
                return ( "scissors wins" );
                game += 1;
            }
        }
    };
    console.log( compare ( userChoice, computerChoice ));
} while (Math.abs(game) < 2);
if (game >= 2) {
    console.log( "You did great. Thanks for playing!");
}
else {
    console.log( "Awww. Too bad. Better luck next time.");
}


#2

@byterockstar83945,
If you use code like

                return ( "scissors wins" );
                game += 1;

the game += 1; will never be executed
as the return-statement will immediately EXIT the function

Try it by using

                game += 1;
                return ( "scissors wins" );

#3

Thank you. I was a little muddled about what the return statement did to begin with. I must have slept through that lesson. I think you saved me a lot of grief down the line! Now to make this code more efficient... as it is, if the computer wins, player wins, computer wins, player wins, etc, it isn't quite a best of 3....


#4

@byterockstar83945,
Was the last comment a question ???
If so could you be more precise in your wording.....


#5

No. Just trying to be funny. You've helped immensely already. Thanks again.