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

Agustin Hernandez
Agustin Hernandez
2,747 Points

Another Way

This works as well!!

var isCorrect = false;
var random = Math.floor( Math.random() * 8 ) + 1;
console.log(random);
var userGuess = prompt("Guess a number between 1 and 8");

if (parseInt(userGuess) === random) {
    isCorrect = true;
} else if ( parseInt(userGuess) > random ) {
    alert("Nice Try! But it's less than " + userGuess);
} else if ( parseInt(userGuess) < random ) {
    alert("Nice Try! But it's greater than " + userGuess)
}

if ( isCorrect ) {
    document.write('<p>Correct! the number was ' + random + '</p>');
} else if ( isCorrect === false ) {
    userGuess = prompt("Guess again it's between 1 and 8");
    if ( parseInt(userGuess) === random ) {
        document.write('<p>Correct! the number was ' + random + '</p>');
    } else {
        document.write('<p>Wrong, the number was ' + random + '</p>');
    }
} 

1 Answer

Steven Parker
Steven Parker
231,269 Points

One thing you will discover about programming is that there will always be more than one solution for any non-trivial task. So in addition to making the code functional, the skills of making code both concise and readable/maintainable are also valuable.

This code seems to hit all 3 objectives, so good job! :+1: