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 trialHoward McConaghy
2,926 PointsWhy is my code not working?
Hi, I tried completing the code myself before going along with the video and can't seem to figure out what is wrong with mine.
//Number guessing game
var upper = 10;
var guess;
var randomNumber = getRandomNumber(upper);
var counter = 0;
var correctGuess = false;
function getRandomNumber(upper) {
var randomNumber = Math.floor(Math.random() * upper) + 1;
return randomNumber;
}
do {
guess = prompt("Guess a number between 1 and 10.");
counter += 1;
if (isNaN(guess)) {
alert("Please guess a number.");
}
if (guess === randomNumber) {
correctGuess = true;
}
} while (!correctGuess);
document.write("<h>You guessed the number!</h>");
document.write("<p> It took you " + guess + " tries to guess the number " + randomNumber + ".</p>");
1 Answer
Steven Parker
231,268 PointsI see two issues:
if (guess === randomNumber) {
Since "guess" is a string, it will never match the number using the type-sensitive equality operator. You can use the normal operator (==
) instead to allow the system to perform type coercion, or you can manually convert one of them to the other type.
document.write("<p> It took you " + guess + " tries to guess the number " + randomNumber + ".</p>");
The number of tries is stored in "count" instead of "guess".
Howard McConaghy
2,926 PointsHoward McConaghy
2,926 PointsNever mind I figured it out - I was comparing a string to an integer.