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

Vince Leung
Vince Leung
4,730 Points

Javascript answer alternative: do while loop

Hi everyone i have a question regarding do while loop for JS. The answer for the teacher for one of his questions was the following.

var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;
var correctGuess = false; //called a flag

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

do {
    guess = prompt("Please guess a number");
    guessCount += 1;
    if (parseInt(guess) === randomNumber) {
        correctGuess = true;
    }

} while (! correctGuess)

document.write ("<h1> You guessed the number!</h1>");
document.write ("It took you " + guessCount + " tries to guess the number " + randomNumber);

'''

While my solution is as follows. The result seems to be the same, or maybe im missing something?

''' Javascript

var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;
var correctGuess = false; //called a flag

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

do {
    guess = prompt("Please guess a number");
    guessCount += 1;

}
 while (parseInt(guess) !== randomNumber)

document.write ("<h1> You guessed the number!</h1>");
document.write ("It took you " + guessCount + " tries to guess the number " + randomNumber);

'''

Thanks!

2 Answers

Thomas Nilsen
Thomas Nilsen
14,957 Points

Nothing wrong with your solution. But when you have a boolean value you can use to validate, I'd prefer that.

If the variable is properly named, it also makes it more readable.

My more of FP approach would be.

const randomNumber = getRandomNumber(10)
Array(randomNumber).fill().forEach(() => `DO your stuff randomNumber times`);