Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Random Number Challenge Solution

Liga Zarina
Liga Zarina
9,447 Points

asking user input with prompt to provide the numbers

I did the code challenge like Dave showed in the video by putting the random numbers in the code when calling the function and it worked as it should. As a practice I thought to rewrite it a bit so that a user would provide the numbers. Theoretically it works BUT the maths doesn't add up properly.

For example, I write 1 for the small number and 10 for the large number and get 91. But if I delete the promt and write the numbers below in the document.write(getRandom()); it works as it should displaying numbers between 1 and 10.

function getRandom(lower, upper) {
    var lower = prompt("Please enter a small number.");
    var upper = prompt("Please enter a large number.");
    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
document.write(getRandom());

I validated both options are no errors come up. Am I missing something?

2 Answers

Thomas Nilsen
Thomas Nilsen
14,957 Points

Because the prompt returns strings. When you sum strings the result will be different

For example '3' + '1' = '31' instead of 3 + 1 = 4

To fix this, you need to parse the prompts:

var lower = parseInt(prompt("Please enter a small number."));
var upper = parseInt(prompt("Please enter a large number."));

Also - there is no need to pass in lower and upper arguments when you declare them inside you function anyway.

Full code:

function getRandom() {
    var lower = parseInt(prompt("Please enter a small number."));
    var upper = parseInt(prompt("Please enter a large number."));

    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
document.write(getRandom());
Liga Zarina
Liga Zarina
9,447 Points

Thanks, makes sense now. Forgot about the parseInt.