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

Megg Gawat
Megg Gawat
2,729 Points

Explain the math?

Can someone explain the math here? I barely understand it.

var randomNumber = Math.floor(Math.random() * (topNumber - bottomNumber + 1)) + bottomNumber;

3 Answers

Hey Megg,

I actually explained how this line works a few months ago in another post.

My explanation. It's pretty extensive, probably overly so, but I hope it helps you understand exactly how that line of code works.

Let me know if you have any questions.

Brandon Berger
Brandon Berger
3,947 Points

Here's the same code broken up into separate pieces.

Check this out: example link

function doMath(){
var topNumber = 10;
var bottomNumber = 1;
var randGen = Math.random();
var a = topNumber - bottomNumber;
var x = a + 1;
var y = x * randGen;
var rounded = Math.floor(y);
var finalAnswer = rounded + bottomNumber; 

var explanation = '<br><br>The random generated number is: ' + randGen + '  <br> The topNumber is: ' + topNumber + ' <br>The bottomNumber is: ' + bottomNumber + '<br><br>The topNumber subtracted by the bottomNumber plus one is : ' + x + '<br>The answer to the above equation multiplied by the random number is: ' + y + '<br>' + y + ' rounded down to the nearest whole number is: ' + rounded + '<br>The rounded number plus the bottomNumber is: ' + finalAnswer;

document.getElementById('mathExplained').innerHTML = explanation;
}

Please don't ask me why i made this. lol

jason chan
jason chan
31,009 Points

Math floor is round to the nearest number less than .4. Random number generated. Add top number subtract botton num + 1 so it doesn't equal zero. Then add bottomnumber again.