Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Working With Numbers The Random Challenge

Eric Jusic
Eric Jusic
4,350 Points

Another solution with 2 inputs, what do you say?

Here is my code for randomizing between 2 inputs, which seems to work:

var lowestNumber = parseInt(prompt("Pick lowest number.")); var userInput = parseInt(prompt("Insert number you want to randomize.")); var rollNumber = Math.floor( Math.random() * (userInput - lowestNumber) ) + lowestNumber; var result = "The random number you got is " + rollNumber; alert(result);

If you have any better solution please suggest.

Thank you :)

3 Answers

Steven Parker
Steven Parker
216,136 Points

Two suggestions:

Add 1 to the range to make it inclusive:
"Math.floor(Math.random() * (userInput - lowestNumber + 1 ) ) + lowestNumber"

For clarity, you might want to ask for "highest number" instead of "number you want to randomize."

Eric Jusic
Eric Jusic
4,350 Points

Thanks Steven for answering.

Can you clarify why this +1 is there? Is this because of Math.random() can give 0 potentially? Even if it gives 0 + lowestNumber will be the lowestNumber? Or I am missing something?

I agree on the second suggestion, I just named it that way in the workspace.

Steven Parker
Steven Parker
216,136 Points

Remember that Math.random generates values approaching but never equal to 1. So when you multiply it by another value, the product will approach but never equal that number. By adding 1, that allows the range to include the high number in the possible values instead of just generating numbers up to but not including that number.

Eric Jusic
Eric Jusic
4,350 Points

Got it now, I forgot on the highest one.

Thank you, Steven, for helping me out again :)