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

Saqib Ishfaq
Saqib Ishfaq
13,912 Points

what's wrong with my code?

my else statement in the end doesnt seem to work ! since i added 'else if' s into the code!

var userInput = prompt('i am thinking of a number between 1 and 6, can you guess what is it?');
var randomNumber = Math.floor(Math.random() * 6) + 1 ;
if (parseInt(userInput) === randomNumber){
 document.write('<p>yay you guessed it right, the number was indeed '+ randomNumber +'.</p>');
}   else if(parseInt(userInput) < randomNumber){
        alert ('sorry number is larger than your guess, want to try again..');
        var guessMore = prompt ('the no is larger than your 1st guess');
            if(parseInt(guessMore) === randomNumber){
            document.write('<p>yay you guessed it right, the number was indeed '+ randomNumber +'.</p>');
        } 
    }else if(parseInt(userInput) > randomNumber){
        alert('sorry number is less than your guess, want to try again..');
        var guessLess = prompt ('the no is less than your 1st guess');
           if (parseInt(guessLess) === randomNumber){
            document.write('<p>yay you guessed it right, the number was indeed '+ randomNumber +'.</p>');
        }       
    }else {
    alert('sorry, your guess is not correct! the number was '+randomNumber+' .');
    console.log(randomNumber);
}
Noah Matsell
seal-mask
.a{fill-rule:evenodd;}techdegree
Noah Matsell
Full Stack JavaScript Techdegree Student 14,010 Points

Hi Saqib,

Following the logic of your if/else if statements, if the user enters a valid number the last else statement will never evaluate--a given number will either be equal to, greater than, or less than the random number.

The only way I can get the last else statement to evaluate is if I enter a letter or special character in which case parseInt(userInput) will equal NaN.

Does that make sense?

1 Answer

Zoltan Parragi
Zoltan Parragi
6,007 Points

Hi, You have too many curly brackets.

if (parseInt(guessLess) === randomNumber){ document.write('<p>yay you guessed it right, the number was indeed '+ randomNumber +'.</p>'); } <-- this is not needed
}else { alert('sorry, your guess is not correct! the number was '+randomNumber+' .'); console.log(randomNumber); }