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

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.