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 trialOmar Farag
4,573 PointsFunction not working
When the alert pops up, "undefined" appears instead of a number value.
function randomNum (bttmNum, topNum) {
Math.floor(Math.random() * (topNum - bttmNum + bttmNum)) + bttmNum;
}
alert(randomNum (11, 14));
3 Answers
Rick Buffington
8,146 Points3 things: 1) When you are multiplying your random number * (topNum - bttmNum + bttmNum) you are being redundant. You are subtracting bttmNum and then adding it again. This would be the same as adding 0 :). I think the idea is to +1 instead of the bttmNum to make up for the random generators decimal value. 2) You aren't assigning your random number to anything
var myNum = Math.floor(...)
3) You aren't returning anything. Your function really needs to return a value in order to be useful.
Hope that helps.
Omar Farag
4,573 PointsFor some reason this function returns values above 14 sometimes...
function randomNum (bttmNum, topNum) {
var dieRoll = Math.floor(Math.random() * (topNum + 1)) + bttmNum;
return dieRoll;
}
alert(randomNum (3, 14));
Rick Buffington
8,146 PointsYou've got it - however, if you compare your Math.floor() setup, you'll see that they subtract the bottom number from the top number and then +1.
var dieRoll = Math.floor(Math.random() * (topNum - bttmNum + 1)) + bttmNum;
Omar Farag
4,573 PointsOk, thanks
Omar Farag
4,573 PointsOmar Farag
4,573 PointsThanks again :)
Rick Buffington
8,146 PointsRick Buffington
8,146 PointsMy pleasure.