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

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Jeff Xu
Jeff Xu
10,291 Points

Guess Counter Wrong?

Hi, i think the we should first set a random guess value when we declare the variable. That way, when we enter the loop, we have a guess ready, and if this guess is wrong then we increase the guess counter. If we declare an empty guess variable, then the first guess will always be wrong when there's a small chance the first guess might just be a hit. the following shows my code, a little different than in the video but that's because i always try to do the exercise first and then see the rest of the vid for solution

function randomNumber(upper) {
  return Math.floor( Math.random() * upper ) + 1;
}

var randomValue = randomNumber(10000);
var guess = randomNumber(10000);
var guessCount=0;

while(guess !== randomValue) {
  guess = randomNumber(10000);
  guessCount++
}

console.log(guessCount);
console.log(guess, randomValue);

2 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

For this problem, I like do...while loop better, not sure if the lectures you're in so far have covered this loop yet.

var randomValue = randomNumber(10000);
var guess;
var guessCount=0;

do {
  guess = randomNumber(10000);
  guessCount++;
} while (guess !== randomValue);

do...while loop runs the loop body before checking for loop condition; whereas while loop check the condition before execute loop body.

Matthew Hicks
Matthew Hicks
9,844 Points

Ah yes but, the guessCount is set at 0 at the start and not 1. The solution in the video does accuratley log the amount of guesses, where as in your solution, should the computer get it right on the very first guess, the while condition would not be met and the amount of guesses would be logged as 0 rather than 1.

Matthew Hicks
Matthew Hicks
9,844 Points

Just to be clear, I was referring to the original post. William's solution of flipping it to a do-while loop does indeed maintain the correct guess count.