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

Omar Farag
Omar Farag
4,573 Points

Function 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
Rick Buffington
8,146 Points

3 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
Omar Farag
4,573 Points

For 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
Rick Buffington
8,146 Points

You'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;