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

Davindar Singh
Davindar Singh
1,951 Points

What if my upper number was (100) and my lower number was (99) Would the final number be? 101

If I am incorrect please explain why? As i'm struggling to understand the formula completely

I was confused also at the beginning but its simple.

The Math.floor() function returns the largest integer less than or equal to a given number

The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1)

I will try to explain to you.

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

In your case Math.floor( Math.random( P.S. RANDOM NUMBER WILL NEVER BE ONE ) * ( 100 - 99 + 1 ) + 99 );

let's do simple math. Math.floor( Math.random( 0.98653245 ) * ( 100 - 99 + 1 ) + 99

Math.floor( Math.random( 0.98653245 ) * ( 2 ) + 99 ) so you do bracket first so 100 - 99 + 1 = 2 next step

Math.floor( Math.random( 0.98653245 ) * 2 + 99) so now multiplication 0.98653245 (this is math random) * 2 = 1.9730649

Math.floor( 1.9730649 + 99 ); is 100.9730649

so Math.floor(100.9730649); is 100 beacouse we dont have whole number Math.floor is makeing the number 100 :) P.S. Sorry for my ENGLISH :)

Davindar Singh
Davindar Singh
1,951 Points

Goce Petrov thank you, I understand it now

1 Answer

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

You'd just get either 99 or 100. What adding + 1 does in JavaScript is simply makes sure the upper number can be returned.

In your example, You wouldn't get 100 returned as the function returns a single integer value that rounds down. I'm not sure why this is, but it's just the way JavaScript inteprets numbers. :-)