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 Create a random number

?? "From 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range." ??

I'm not entirely absorbing what this means. Is there a way to explain what this means in a different way?

If I give it math.random() * 6 would it then give me a response of 0-5 as it excludes the 6? Thanks! Blake

1 Answer

Ionut Costica
Ionut Costica
737 Points

Actually, according to the Mozilla Developer Network documentation:

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. [italics added]

So that means that it returns a number that is greater or equal to 0 and less than 1. Scaling in this context means multiplying by another number to set the non-inclusive upper bound of the random number you get to a new number (therefore to get numbers between 0 and that new number, just use Math.random() * max_desired_number). If you instead want to set the lower bound, just add the lower bound to the Math.random call, like so: 5 + Math.random() (which will give us a number between 5 and 6).

Putting it all together, if you want a random number x between your_min_number and your_max_number such that your_min_number โ‰ค x < your_max_number the required expression would be your_min_number + Math.random() * (your_max_number - your_min_number).

Ginger had it mostly right, but she forgot to factor in the fact that the numbers are not integers and that adding 1 to the expression will also shift the ending point of the expression.

This is awesome. Thank you so much!!!