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

Willemijn B
Willemijn B
5,577 Points

Using 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
Sean T. Unwin
28,660 Points

When 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
Ken Stone
29,701 Points

One 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
Willemijn B
5,577 Points

It'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!