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 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
229,644 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".