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

Dan MacDonagh
Dan MacDonagh
4,615 Points

Went about it a different way.

So I decided to pause the video and try and write the code myself to see how my process differed from Daves. This is what I came up with.

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 a number between 1 and 10");
} while (parseInt(guess) !== randomNumber);
document.write("<p>The random number was " + randomNumber + "</p>");
document.write("<p>It took you " + guessCount + " tries to get it right.</p>");

The end result had the same functionality as his process (he added an If statement inside the loop). Is there anything wrong with my method?

The way you've written it actually makes it easier to understand!

Clara Roldan
Clara Roldan
3,074 Points

I thinks it's easier to read this way, but then the way it's shown in the video explains the use of variables as flags, which is also good to know.

4 Answers

Jason Anders
Jason Anders
Treehouse Moderator 145,858 Points

Hey Dan, I don't see anything wrong with your code... It does exactly what it is supposed to do.

Thank-you for sharing your code variation in the forum. Often there are many ways to accomplish the same thing (especially with JavaScript), so it great that others try it their way and share their code (whether it works or not).

So, keep experimenting and keep sharing!

Jason :)

Sage Elliott
Sage Elliott
30,003 Points

That's the fun thing about coding! There is never just one way to do things :)

Sean T. Unwin
Sean T. Unwin
28,690 Points

Nice, intuitive take on it, Dan. Cheers.