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, Part II

Daniel Campbell
Daniel Campbell
10,148 Points

random number is out of range

var lower = prompt("enter lower limit");
var upper = prompt("enter upper limit");

function getRandomNumber(lower, upper) {
  return Math.floor(Math.random() * (upper - lower + 1)) + lower; 
}

alert(getRandomNumber(lower, upper));

Hi, I'm getting numbers out of range and can't seem to figure it out.

2 Answers

Cheo R
Cheo R
37,150 Points

Hello Daniel, you're on the right track. Remember that prompt() takes in a string, so you just need to convert the input with parseInt().

var lower = parseInt(prompt("enter lower limit"));
var upper = parseInt(prompt("enter upper limit"));

function getRandomNumber(lower, upper) {
 // document.write("Lower: " + typeof lower);
  return Math.floor(Math.random() * (upper - lower + 1)) + lower; 
}

alert(getRandomNumber(lower, upper));
Daniel Campbell
Daniel Campbell
10,148 Points

Hi Cheo,

Thank you. It works! I tested to see if the prompt input was a number before using it in the function.

if ( isNaN(lower) || isNaN(upper)) {
throw new Error('oops');
}

I read that if an Integer is input in the prompt it doesn't need to be converted. I guess that's not true.