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 Solution

Dan Putnam
seal-mask
.a{fill-rule:evenodd;}techdegree
Dan Putnam
Front End Web Development Techdegree Student 8,596 Points

My random numbers are never = to the min or max

I've followed the video exactly but my random number never will output as the min or max. Only numbers between the min or max, unlike it shows in the video. Is Math.random messing up?

function random2(upper, lower){
  return Math.floor(Math.random() * (upper - lower+1)) + lower; 
}
document.write(random2(1,5));
Jason Anders
Jason Anders
Treehouse Moderator 145,860 Points

You need to flip the arguments around in the function.

Use

function random2(lower, upper) {

instead of

function random2(upper, lower) {

The rest of the code is fine. The problem lies here only.

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hey Dan,

The reason you are not getting the "upper" or "lower" limit numbers is just a simple ordering of the arguments for the function. Instead of upper, lower, flip it to be lower, upper. The way the arguments are set up now, the function is doing 1 - 5 + 1 instead of 5 - 1 + 1.

Hope that makes sense. Keep Coding! :dizzy:

Dan Putnam
seal-mask
.a{fill-rule:evenodd;}techdegree
Dan Putnam
Front End Web Development Techdegree Student 8,596 Points

Silly error, thanks! I was able to do some interesting debugging at least.

I wonder why the output still seemed reasonable though. Math.floor must make negative numbers positive?

Jason Anders
Jason Anders
Treehouse Moderator 145,860 Points

I've noticed that too.

Just haven't done the research yet as to why it reacts and outputs that way with a negative number. Lol. :)

Glad you got it all cleared up. :dizzy: