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) Creating Reusable Code with Functions Random Number Challenge, Part II Solution

kabir k
PLUS
kabir k
Courses Plus Student 18,036 Points

Is my function also correct?

I am curious about the version of my code for the flexible random number generating function.

Here's the Teacher's version:

function getRandomNumber(lower, upper) {
  return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
alert(getRandomNumber(2, 9));

And here's my version:

function getRandomNumber(lower, upper) {
  return Math.floor(Math.random() * upper ) + lower;
}
alert(getRandomNumber(2, 9));

My questions are:

  1. Is there a difference between the two and if there is, what is the difference and is my version also correct?

  2. If my version is also correct, why are we subtracting lower from upper in the Teacher's version?

1 Answer

Yes, there is a clear difference between the two. To help you understand everything better:

Math.random();

Returns a random float between 0 and 1, with 1 being excluded.

Math.floor();

Returns the closest integer, rounding down.

Now what the teacher does, is creating a function that gets a random number between 2 and 9. To do this, he takes the difference between the two numbers and adds one. This number times a random value between 0.00-0.99, will leave you with something between 0.00 and 7.99. Adding the base number 2, will give 2.00-9.99. If you floor this value, you will get a integer between 2 and 9.

With your method, you can get anything between 2.00-11.99. Thus, your function is invalid.