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) 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
231,269 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
231,269 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 :)