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

Not sure what I'm doing wrong.

When I try this:

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

it works properly.

When I try this:

var lowNum = prompt('Please choose a number.');
var highNum = prompt('Please choose a number larger than ' + lowNum + '.');

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

it does not.

There is no error message in the console, but a number outside the given range appears.

1 Answer

Ryan S
Ryan S
27,276 Points

Hey Christopher,

The issue is that the prompt() function will always return a string. So whatever numbers you give it will actually be strings and I think that is causing strange things to happen in your getRandomNumber() function.

If you use parseInt() to convert them into integers then it should solve your problem:

var lowNum = parseInt(prompt('Please choose a number.'));
var highNum = parseInt(prompt('Please choose a number larger than ' + lowNum + '.'));

Thank you.