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 trialWillemijn B
5,577 PointsUsing prompts returns two values
At first I only created a function and used console.log
to view the result (first part of my code) which worked fine - however, then I tried using prompts and document.write
to get input from the user and show it on the page. In this case I keep getting a result that's either outside of the desired range (e.g., 44 when I entered 1 and 6), or something like '09'. It's always two digits.
I feel like I remember Dave discussing this issue in an earlier video, but I can't find it and I can't figure out how to fix this issue. Not sure either if I called the function correctly, anyway.
function randomNumberGenerator(min, max) {
var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNumber;
console.log(randomNumber);
}
var min = prompt("Enter a minimum number");
var max = prompt("Enter a maximum number");
document.write("Your random number is " + randomNumberGenerator);
Edit to add: I realize there's no parseInt
for the user input here either. How should I use that here?
3 Answers
Sean T. Unwin
28,690 PointsWhen calling the randomize function in document.write()
, the function parenthesis and parameters are missing.
Good call on the parseInt()
as well.
The following is one way to get the desired results:
/** function ... **/
var min = parseInt(prompt("Enter a minimum number"));
var max = parseInt(prompt("Enter a maximum number"));
document.write("Your random number is " + randomNumberGenerator(min,max));
Ken Stone
29,703 PointsOne other thing is that if you want to see the randomNumber printed to the console but the return line below the console.log line.
console.log(randomNumber);
return randomNumber;
Willemijn B
5,577 PointsIt's working now! I didn't remember that forgetting to use parseInt causes the random number to return as a two-digit string. Using parseInt fixed that. And I actually used the parameters at first - this was my attempt to fix it, but I understand now that the lack of parseInt was the culprit. Also totally forgot about return ending the function. I guess I was a little tired ;)
Thanks Ken and Sean!