Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

Howard McConaghy
Howard McConaghy
2,926 Points

Why 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>");
Howard McConaghy
Howard McConaghy
2,926 Points

Never mind I figured it out - I was comparing a string to an integer.

1 Answer

Steven Parker
Steven Parker
210,425 Points

I 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".