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

How can I make this so that variables defined by prompts set the numbers?

var L = prompt("Pick a number less than 100");
var U = prompt("Pick a number greater than 100");

function randomNumber(U, L){
return Math.floor(Math.random() * (U - L + 1)) + L
}

alert(randomNumber(U,L));

2 Answers

andren
andren
28,558 Points

You can use the parseInt function which will convert a string (which is what the prompts return) into an int. Like this:

var L = parseInt(prompt("Pick a number less than 100"));
var U = parseInt(prompt("Pick a number greater than 100"));

I see so the problem was that I didn't convert the numbers to an integer?

andren
andren
28,558 Points

Yes. For JavaScript to treat something as a number it has to be stored as an integer. Numbers stored in strings are treated as text. Some operators like + performs one action on strings (concatenation) and a different one on numbers (addition). So when performing math operations it's important that the variable is stored as the correct type.