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 does not work as expected

Hi, I try to run his code

var randomNbre = randomNumber (1); var guess; var guessCounter = 0; var chances = 10 var correct = false;

function randomNumber (upper) { return Math.floor(Math.random() * upper) + 1; }

while (guessCounter < 10) { guess = prompt ("I'm thinking to a number between 1 and 10 which one is it ?"); if (parseInt (guess) === randomNumber) { correct = true; break; } alert("You still " + chances + " Chance. Correct number is " + randomNbre); chances--; guessCounter++; }

if (correct) { document.write("Yep"); } else { document.write("you should refresh the page"); }

console.log(correct);

but it's not work because even if I find the right number, my variable correct is still false. Can you help me please ?

Thank you.

3 Answers

Steven Parker
Steven Parker
229,645 Points

:point_right: You are not comparing your stored random number to the input.

When you pick the random number, you store it in a variable named randomNbre, but when you check the input, you compare it to randomNumber (which is the name of the function).

if (parseInt (guess) === randomNumber)  // <-- should be "randomNbre"

Now that you can fix the issue, I'm guessing you will also want to change the range on the first line (back to 10?).

Erik Nuber
Erik Nuber
20,629 Points
var randomNbre = randomNumber(10); 

var guess; 
var guessCounter = 0; 
var chances = 10; 
var correct = false;

function randomNumber (upper) { 
          return Math.floor(Math.random() * upper) + 1; 
}

while (guessCounter < 10) { 
guess = prompt ("I'm thinking to a number between 1 and 10 which one is it ?"); 
if (parseInt(guess) === randomNbre) { 
      correct = true; 
      break; 
} 

chances--; 
alert("You still have " + chances + " chances to guess."); 
guessCounter++;

 }

if (correct) { 
document.write("Yep"); 
} else { 
document.write("you should refresh the page"); }

console.log(correct);

I just fixed some of the spacing issues and missed quotation markers. The biggest issue was that your if statement was comparing parseInt(guess) to randomNumber instead of the variable you created to hold the random number.

Also, I took out the statement in the alert about sharing the random number while they are guessing.

Thank you guys. Noob mistake XD.