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

Abdullateef Almalouhi
Abdullateef Almalouhi
1,955 Points

Do you think my code is OK?

Is my solution to this challenge correct?

var num1 = parseInt(prompt("Enter a number"));
var num2 = parseInt(prompt("Enter another number"));

function randomNum(num1, num2) {
     if (num1 > num2) {             
  var numGen = Math.floor(Math.random() * (num1 - num2 + 1)) + num2;
   return numGen;
} else {

  var numGen = Math.floor(Math.random() * (num2 - num1 + 1)) + num1; 
  return numGen;
alert(randomNum(num1, num2));

2 Answers

arthur tucker
arthur tucker
2,021 Points

That seems to work well, though I went another route. I contained everything within the function to ensure no outside source could effect the variables, make sure its not globally accessible.

Hi. Why is there a plus (+) 1 inside (num1 - num2 + 1)?

And one other thing, is it a good idea to check also if the two inputs are equal? For example the user puts in 5 in the first prompt and then enters 5 again in the second prompt? Thanks