Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Learn one solution for breaking out of the loop when a user guesses the random number.
Resources
Display a countdown
The following demonstrates how you might count down from 10 to 1 and display the remaining number of guess attempts to the user.
for ( let i = 10; i >= 1; i-- ) {
let guess = prompt(`You have ${i} tries to guess a number between 1 and 10.`);
if ( parseInt(guess) === randomNumber ) {
message = `It took you ${i} tries to guess the number ${randomNumber}.`;
break;
} else {
message = `You did not guess the number. It was ${randomNumber}.`;
}
}
Take the guessing game further
You can use conditional statements to give the player hints about the number to guess. Consider the following code:
const main = document.querySelector('main');
const randomNumber = getRandomNumber(10);
let message;
let guess = prompt(`Guess a number between 1 and 10.`);
function getRandomNumber(upper) {...}
for ( let i = 9; i >= 1; i-- ) {
if ( +guess > randomNumber ) {
guess = prompt(`Guess a lower number. You have ${i} more tries.`);
} else if ( +guess < randomNumber) {
guess = prompt(`Guess a higher number. You have ${i} more tries.`);
} else if ( +guess === randomNumber ) {
message = `You guessed the number! It was ${randomNumber}.`;
break;
}
message = `You did not guess the number. It was ${randomNumber}.`;
}
main.innerHTML = `<h1>${message}</h1>`;
If the player's guess is higher than the number to guess, the prompt dialog instructs them to guess a lower number. If their guess is lower, the prompt hints at entering a higher number.
You need to sign up for Treehouse in order to download course files.
Sign up