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 `do ... while` Loops

There is a much shorter way?! (leave out the currentGuess variable)

Instead of using a new Boolean variable inside of the if statement we could use the while condition to check wether the guess was the random number. This would be much more readable, shorter and memory efficient( one bool ;) and an if statement)

Is there any reason why Dave did that instead of this :

var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;

function getRandomNumber( upper ) {
  var num = Math.floor(Math.random() * upper) + 1; 
  return num;
}

do {
  guess = prompt("Guess my number between 1 and 10!");
  guessCount += 1;
} while ( parseInt(guess) !== randomNumber)

alert("You got my number after " + guessCount + " attemps!");

2 Answers

Steven Parker
Steven Parker
229,644 Points

I'm just guessing, but perhaps it was just an opportunity to illustrate the concept of using a Boolean value as a loop control, which can be handy in more complex programs.

I agree that in this case, simply testing the condition directly in the loop conditional clause is more concise and easily read.

I did mine the exact same as yours ;)