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 Build a Random Number Guessing Game

Prakhar Patwa
Prakhar Patwa
11,260 Points

Build a Random Number Guessing Game

my code is

var randomNumber = Math.floor(Math.random() * 6) + 1 ; var guess = prompt("i am thinking the number between 1 and 6 , what it is?") if(parseInt(guess) === randomNumber){ document.write("<h1> You Guess The Right Number </h1>") }else if(!NaN){ document.write("<h1>you have entered the invalid entry " + guess + "</h1>") }else{ document.write("<h1>You Guess the wrong number,the random number was " +randomNumber+ "</h1>") }

I also want to show that suppose if user entered the string so it should show invalid entry . Every time it showing invalid entry even on integer.

1 Answer

Hey Prakhar,

I noticed in what I could gather from your code that you're checking if (!NaN). Your if statements should be almost always comprised of dynamic data. if (!NaN) is a static if-statement that will always evaluate to true because you are saying "If NaN is a falsey value, do this code." NaN will always be a falsey value, so the if statement always executes which is why you get the invalid entry message every time an incorrect guess has been made.

I reformatted your code and added a few things:

var randomNumber = Math.floor(Math.random() * 6) + 1 ;
//Added semicolon to guess
var guess = prompt("I am thinking of a number between 1 and 6.  What is it?");
//Added 10 to parseInt so that it will explicitly get the number inside guess from the base 10 system
if(parseInt(guess, 10) === randomNumber){ 
document.write("You Guessed The Right Number!") 
}
//Check to see if guess is not a number
else if (isNaN(guess)) { 
//Added semicolon
document.write("You have entered the invalid entry " + guess); 
}
else { 
//Added semicolon
document.write("You guessed the wrong number.  The random number was "+randomNumber);
 }
Prakhar Patwa
Prakhar Patwa
11,260 Points

okay i got it now..... in place of !Nan it should be written like isNaN(variable_name) thankx alott Marcus Parsons.

Absolutely, Prakhar! :) You are very welcome!