I'm trying to run this function until the player or the computer wins 5 times. Without the while loop, it runs one time and everything works fine. As soon as I add a while loop, the function still runs only once and it gives me an undefined return.
function playToFive() {
console.log('Let\'s play Rock Paper Scissors');
var playerWins = 0;
var computerWins = 0;
while (playerWins === 5 || computerWins === 5) {
if (humanVsMachine === 'player') {
playerWins += 1;
} else if (humanVsMachine === 'computer') {
computerWins += 1;
}
return [playerWins, computerWins];
}
}
console.log(playToFive());
Your while loop will actually never execute, since you're checking for equality and both
playerWinsandcomputerWinsare0initially.You may be looking for a condition more like this:
Note that we're using the logical AND
&&instead of the logical OR||. This is because you don't want to keep looping until both of them win. The logical OR means that even if the computer has won but the player hasn't, we'll continue looping. Only one of the conditions needs to be true for the whole statement to be true.When we use the logical AND, if one of them is false (meaning, if only one player has reached 5 wins already), then we will break out of the loop as we should.
The next problem is that you have a return statement in your while loop, so after the first execution, even if 5 wins haven't been reached yet, it will return the array of the player's wins and the computer's wins.
You should put the return statement after the loop so that you run the loop 5 times and then return after somebody has won.
And finally, since you haven't provided the rest of the code, I'm not sure if
humanVsMachineis actually defined; if you defined that outside of the function then you're good to go.