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

When I execute correctGuess always returns true. Please help?

So I thought I was really good at guessing, but then started repeating values. I can't see what the problem is though :( Here's my code:

var correctGuess = false
var randomNumber = (Math.floor(Math.random()*6))+1;
var guess = parseInt(prompt("I'm thinking of a number from 1-6, can you guess what it is"));

if (randomNumber === guess) {
    correctGuess = true;
}
else if (guess < randomNumber) {
  var guessLess = parseInt(prompt("Too small, guess again!"));
  if (guessLess === randomNumber) {
    correctGuess = true;
  }
}
else if (guess > randomNumber) {
  var guessMore = parseInt(prompt("Too big, guess again!"));
  if (guessMore === randomNumber) {
    correctGuess = true;
  }
}

else {
  document.write("Fail! The number was "+randomNumber+".");
}
if (correctGuess = true) {
  document.write("Way to go! The number is "+randomNumber+"!");
}

1 Answer

In your last if statement you are missing an equals sign. This means you are actually setting correctGuess to be true instead of checking if it is true.

// instead of...
if (correctGuess = true) {
  document.write("Way to go! The number is "+randomNumber+"!");
}

// do this!
if (correctGuess === true) {
  document.write("Way to go! The number is "+randomNumber+"!");
}

Tyvm! This right here was like waking up on christmas morning! :)