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 Numbers The Math Object Random Number Challenge – Solution

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
Cameron Childres
11,817 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.

Thank you very much !