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

Tou Lee
Tou Lee
6,608 Points

Random Number Challenge

Why did he do

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

and not

function randomItem(upper, lower) { return Math.floor( Math.random() * lower ) + upper; }

? It would yield the same right???

1 Answer

Ryan Schurton
Ryan Schurton
13,815 Points

Hey Tou,

Let break this down.

Remember Math.random() function returns a floating-point, number in the range 0, 1 that is, from 0 up to but not including 1.

so lets say for example Math.random() return 0.6524051737505943. lets try this with the second function your provided :

function randomItem(upper, lower) { 
    return Math.floor( Math.random() * lower ) + upper; 
}

console.log(randomItem(10, 20));

remember the rule with math we execute the stuff in the brackets first.
0.6524051737505943 * 10 = 6.524051737505943

we call Math.floor with the value of 6.524051737505943 which will round down to 6 and then add our upper value of 20 our final random number will be 26 which is outside of the range of numbers we passed. Remember we passed the values 10 and 20 to the function randomItem.

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

console.log(randomItem(10, 20));

Again brackets first:

10 - 20 + 1 = -9

-9 * 0.6524051737505943 = -5.871646563755349

= -5.871646563755349 + 20

-6 + 20 = 14

The correct function that was provided in the video example will return 14 as a random number.

As a Summary in the first functions we passed the values 10, 20 and got the return value of 26. In the correct solution we provided the values of 10, 20 and get the return value of 14 back. so in short they will not yield the same values.

Hope this was helpful Tou