JavaScript JavaScript Numbers The Math Object Random Number Challenge – Solution

Jeffrey SPICHER
seal-mask
.a{fill-rule:evenodd;}techdegree
Jeffrey SPICHER
Front End Web Development Techdegree Student 7,548 Points

Hello why does my code tells me : here is your nan number between 1 and four instead of you have to pick a number?

// Collect input from a user

const userNumber = prompt('Pick a number'); console.log(userNumber);

// Convert the input to a number

const UserInNumber = parseInt(userNumber); console.log(UserInNumber);

 // Use Math.random() and the user's number to generate a random number

if (userNumber) {

const UserRandomNumber = Math.floor(Math.random() * UserInNumber) + 1;

// Create a message displaying the random number

 document.querySelector ('main').innerHTML = 

<h1>Here is your random number ${UserRandomNumber} between 1 and ${userNumber}</h1>;

} else { document.querySelector ('main').innerHTML = '<h1>You have to pick a number</h1>';

}

2 Answers

Cameron Childres
MOD
Cameron Childres
Treehouse Moderator 11,681 Points

Hi Jeffrey,

This is because you're using the variable userNumber as the condition for your if statement. Since userNumber is defined with a prompt it will always return a string, which is considered "truthy". There are two exceptions: if you click "cancel" on the prompt it will return null, or if you click "okay" without anything entered it will return an empty string, which are both falsy and will execute your else statement.

If you change the condition to UserInNumber instead you'll be checking the result of parseInt() which will return NaN for strings and 0, executing your else statement. You'll want to change userNumber to UserInNumber in the template literal as well or you could end up with messages containing things like "..and 3.75" or "..and 52cats" instead of an integer.

One last tip -- check out the "markdown cheatsheet" linked below the comment box for help with formatting your code on the forum, it will make it easier to read and prevent characters from being dropped like the backticks around your template literal.