I’m new to Javascript, and I’m trying to wrap my head around while loops. I understand their purpose, and I think I understand how they work, but I’m having trouble with them.
I want the while value to repeat itself until two random numbers match each other. Currently, the while loop only runs once, and I need to run it again if I want it to repeat itself.
How can I set this loop up so that it will automatically repeat the if statement until diceRollValue === compGuess? Thanks.
diceRollValue = Math.floor(Math.random()*7);
compGuess = Math.floor(Math.random()*7);
whileValue = true;
while (whileValue) {
if (diceRollValue === compGuess) {
console.log("Computer got it right!")
whileValue = false;
}
else {
console.log("Wrong. Value was "+diceRollValue);
whileValue = false;
}
}
That’s because you’re only executing the random number generator outside of the while. If you want two fresh numbers they need to be executed within the while statement. Something like the following:
If you wanted to refactor it, you can use
breakto quit the loop (instead of using a variable) as well: