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

var num = Math.floor(Math.random() * upper) + 1; What exactly does 'upper' do? Dave added it some videos back

function getRandomNumber( upper ) { var num = Math.floor(Math.random() * upper) + 1; } Here's more

3 Answers

Jerry Hoover
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jerry Hoover
Full Stack JavaScript Techdegree Graduate 25,815 Points

Upper is the name of the variable that represents the highest number that this function will produce. If upper=4, then this will return a random number between 0 and 4. If upper is set to 216 then it will produce a random number between zero and 216.

It does this by multiplying the result of math.random (a number between 0 and 1) by the value of upper, resulting in a float between 0 and the value of upper. Math.floor then rounds the value down to the nearest integer such that, if the result is 41.1657843, the stored value in ‘num’ will be 41.

Nayonna Purnell
seal-mask
.a{fill-rule:evenodd;}techdegree
Nayonna Purnell
Full Stack JavaScript Techdegree Student 6,683 Points

var num = Math.floor(Math.random() * upper) + 1; upper signifies the top number in the range of random numbers. Example: if we wanted a random number from 1 -6. Six signifies the upper number.

Math.random() gives us a number from 0 to 1. Math.floor- rounds the number down. In this particular example, Math.floor(Math.random() * upper) would give us a number from 1-5. The +1 would give us 6.

Thank you both. In other words upper is just a place holder