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

kevinkrato
kevinkrato
5,452 Points

'do.. while' loop. I'm doing something wrong... not sure what.

I wrote out this code and I have been testing it out. No matter what answer I enter the answer is always right. I've been moving the code around a bit, I figured the document.write would only trigger if I put it inside of the if conditional statement, but evidently that didnt make a difference. Any ideas?

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

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

do { guess = prompt('I am thinking of a number between 1 and 10. What is it?'); guessCount += 1; if (parseInt(guess) === randomNumber); { correctGuess = true;
document.write('<p> you guessed right! </p>'); } } while ( correctGuess = true )

Pavol Kocalka
Pavol Kocalka
9,961 Points

There are following problems.

  1. Omit ';' before '{' in this code if (parseInt(guess) === randomNumber); {
if (parseInt(guess) === randomNumber) { 
  correctGuess = true;
  document.write('<p> you guessed right! </p>'); 
  }
  1. you need double or triple '===' in bolleans. so correct bollean statement. also you want zour loop run while correct Guess is false not true so correct boolean should be likebottom. and also add ';' at the end of the statement.
while ( correctGuess === false );

FULL corrected code

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

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

do { 
  guess = prompt('I am thinking of a number between 1 and 10. What is it?'); 
  guessCount += 1; 

  if (parseInt(guess) === randomNumber) { 
    correctGuess = true;
  document.write('<p> you guessed right! </p>'); 
  }

} while ( correctGuess === false );

1 Answer

Steven Parker
Steven Parker
229,644 Points

Pavol is correct that the stray semicolon between the conditional expression and the code block is what causes the code block to run always.

But you don't need to do comparisons on booleans. You can test them directly, or just invert them with "!" if needed (as is the case here):

} while ( !correctGuess );