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 Basics (Retired) Making Decisions with Conditional Statements Improving the Random Number Guessing Game

Monika Frankowska
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Monika Frankowska
Full Stack JavaScript Techdegree Graduate 20,279 Points

I'm getting you guessed the number only when I guessed it in the first prompt. Can't find the mistake in code.

I can't find what's wrong with my code. When I guessed the number in the first prompt or not guessed it at all everything is fine. The code is not working when I guess the number in the second prompt, I still get the information that I'm wrong.

var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;
var guess = prompt('I am thinking of a number between 1 and 6. What is it?');

if (parseInt(guess) === randomNumber ) {
  correctGuess = true;
} else if(parseInt(guess) < randomNumber) {
    var guessMore = prompt("The number is higher than your guess, you have a second chance");
    if (parseInt(guessMore === randomNumber)){
    correctGuess = true;
    }

} else if(parseInt(guess) > randomNumber) {
  var guessLess = prompt("The number is lover than your guess, you have a second cnhance");

  if (parseInt(guessLess === randomNumber)){
  correctGuess = true;
  }
}


if (correctGuess){
  document.write("<p>You guessed the number!</p>");
}else{
  document.write("<p>Wrong! Th number is " + randomNumber + ".</p>");  
}

2 Answers

hello. i think this is what is causing the problem

else if(parseInt(guess) < randomNumber) {
    var guessMore = prompt("The number is higher than your guess, you have a second chance");
    if (parseInt(guessMore === randomNumber)){
// here you are comparing the values and trying to pareInt at the same time.
    correctGuess = true;
    }
// it should be
if(parseInt(guessMore) === randomNumber) {
}

i hope this solves your problem

Here is the wrong part

if (parseInt(guessLess === randomNumber)){
  correctGuess = true;
  }

You need to close parseInt parentheses and then compare to random number. Here is correct code:

if (parseInt(guessLess) === randomNumber){
  correctGuess = true;
  }