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 Solution

Kate Petry
PLUS
Kate Petry
Courses Plus Student 9,432 Points

Further explanation needed on the Random Number Challenge

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

Can someone explain why I need to add lower at the the end? I understand why I add the 1 but why is it necessary to add lower?

1 Answer

Kris Phelps
Kris Phelps
7,609 Points

Hi Kate,

It's because you need to set the lower bound. Let's say you need a random number between 5 and 10.

If the equation were:

Math.floor(Math.random() * (upper + 1)) + lower;

You could get the result of Math.floor(.9 * (10 + 1)) + 5 = 14 (which isn't good since your upper bound is 10)

If the equation were:

Math.floor(Math.random() * (upper + 1));

You could get the result of Math.floor(.1 * (10 + 1)) = 1 (which isn't good because you wanted a number between 5 and 10)

By subtracting the lower bound(lower) and adding that back, you can guarantee that whatever number is generated, falls within the range you need.