Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Akash Sharma
Full Stack JavaScript Techdegree Student 14,147 PointsUsing a while loop until right number was guessed between 1-6.
Here is a solution for this:
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
var correctGuess = false;
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');
while (!correctGuess)
{
if (parseInt(guess) === randomNumber ) {
document.write('<p>You guessed the number!</p>');
correctGuess = true;
} else {
// document.write('<p>Sorry. The number was ' + randomNumber + '.</p>');
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');
}
}
1 Answer
Steven Parker
243,318 PointsYou didn't reference which course page you were working on. This code can be compacted a bit using a "do...while" loop. It could be that's what comes next in the course.
Another enhancement might be to allow a way out without guessing. Adding this code to the loop will let you quit by using the "cancel" button:
if (guess == null) {
document.write('<p>You gave up? It was ' + randomNumber + '</p>');
break;
}