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

Tom Price
Tom Price
5,670 Points

Strange problem - can't work it out. Help!

Hi everyone. My code looks like this at the moment:

function randomGenerator(number1, number2) {
  if (number1 < number2) {
    var low = number1;
    var high = number2;
  } else {
    var low = number2;
    var high = number1;
  }
  var randomNumber = Math.floor(Math.random ()* (high - low) + 1 + low);
  return randomNumber;
}
alert ('Your random number is ' + randomGenerator(parseInt(prompt('Choose your first number.')), parseInt(prompt('Choose your second number.')) + '.'));

The last line is a bit of a mess, but I just wanted to see if I could use prompts to pass arguments to the randomGenerator function.

It all seemed to work, but I've across a problem...

When using prompts to pass arguments, and the number2 parameter is lower than number1 (ie. number1 = 10, number2 = 1), it says that the returned value is not a number when the function is called.

It's fine the other way round, and when you pass arguments to the function as numbers, e.g., alert(randomGenerator(10, 1)); it also works fine.

What's going on? I can't work it out and it's really annoying me.

Thanks in advance!

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Tom,

It was a little hard to find at first, but it's a simple issue of your full stop string been on the wrong side of the function call. Move it down one parenthesis, and magic happens!

alert ('Your random number is ' + randomGenerator(parseInt(prompt('Choose your first number.')), parseInt(prompt('Choose your second number.'))) + '.');

Happy coding!

Tom Price
Tom Price
5,670 Points

Ahhhh I see.

Thanks a lot for the help, Chris. Rapid response, too!

Chris Shaw
Chris Shaw
26,676 Points

No problem, I'm back to my old forum stalker mode... j/k.