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

Casey Metz
Casey Metz
3,209 Points

Not sure why the "if" conditional is necessary within the loop, instead of the "while" condition sufficing.

I get why the provided answer works, but I don't get why the code below doesn't work. It doesn't do anything at all.

My logic was that: The first var guess creates an empty box, then the loop runs for the first time automatically because it's a "do" loop, then prompt should pop up (but it doesn't?) and give "guess" a value, then the "while" condition evaluates whether the "guess" value keeps the loop running or not.

What am I missing? Why is the "if" conditional necessary? Is it a variable scope problem?

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("I'm thinking of a number between 1 and 10. Can you guess it?");
  guessCount += 1;
  }
} while ( parseInt(guess) !== randomNumber )

documet.write("You guessed it!");
document.write("It took you " + guessCount + " tries to guess the number.");
Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Also you're missing a semicolon at the end of the do while, but I'm guessing Javascript is inserting that for you. And at the next to last line, the document.write is misspelled. I changed out the document.write to console.log, fixed the extra curly brace and your code ran in my developer tools like a charm!

2 Answers

Your code would work however you have an additional curly brace before the while condition. Try 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("I'm thinking of a number between 1 and 10. Can you guess it?");
  guessCount += 1;
} while ( parseInt(guess) !== randomNumber )

documet.write("You guessed it!");
document.write("It took you " + guessCount + " tries to guess the number.");
Casey Metz
Casey Metz
3,209 Points

Thanks so much! I'm relieved that my logic was sound, but I need to improve on catching these syntax errors!