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
Peng-Wen Lai
Courses Plus Student 595 PointsI can't get the function part..
function getRandomNumber( upper ){ var num = Math.floor(Math.random() * upper) + 1; return num; }
I can't get:
1) why we don't need to define upper using var?
2) can somebody explain the
Math.floor(Math.random() * upper) + 1; return num;
this part?
Thanks!!
1 Answer
Chyno Deluxe
16,936 Points1) the parameter upper is the variable name so you wouldn't have to declare it as anther variable.
2) the line of code below explained
/**
* return a random number between 0 and upper
* @param { Number } upper - max number possible
* @return { Number } - Random number between 0 and upper
*/
getRandomNumber( upper ) {
var num = Math.floor( Math.random() * upper ) + 1;
return num;
}
/*
* (Math.random() * upper) + 1
* ========================-
* Math.random() - returns a floating number
* between 0 and 1 but will never return 1
*
* multiplying random number by upper
* sets max returned random number
*
* adding + 1 will allow upper
* number to be returned
*
* Math.floor() - will convert a floating integer
* into a rounded number
*
*/
I hope this helps.