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 Solution

Donovan Matthysen
Donovan Matthysen
4,370 Points

Get lost when he starts talking about 1 to z and x to z (2:58--->)

JavaScript Basics video https://teamtreehouse.com/library/javascript-basics/working-with-numbers/the-random-challenge-solution.

Get lost when he starts talking about 1 to z and x to z (2:58--->) This was not covered or am I missing something?

2 Answers

Could you explain a little more on how you are getting lost? Is it the letters z and x that are confusing you or is it the logic of Math.random() with a set minimum and maximum range?

Letters X and Z:

The teachers is using random variables (X and Z) for the range of numbers. For instance, if you wanted a random number between 20 through 50, then x would equal 20 and z would equal 50. If you wanted the random number range to be between 1 and 50 then that is where you get 1 and z equaling 50.

Math.random logic for minimum and maximum range:

Math.random() will give us a floating point (a decimal number) between 0 and less than 1 (0.999...). Then, multiplying that random decimal by the difference of the maximum range and minimum range (plus one) will give us a number between 0 and the total possible numbers within the range that we want. Finally, we need to add the minimum number because we are raising the bottom of the range (currently 0) to the minimum number that we want.

Let's say we want a number between 40 and 60. There are a total of 21 possible numbers within that range (because we are including 40 and 60 as possible results). So Math.random() * (21) will give us any number between 0 and 20.999... If we add the minimum number (40) to both sides of the range, we get 40 through 60.9999. The Math.floor method will remove any decimal so we are left with 40 through 60.

If anyone sees anything wrong with what I said, please correct me.

I hope that helps you!

Zubair Siddique
Zubair Siddique
4,889 Points

You've relieved the pain, Michael. :-)

I am glad to help!