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 Numbers The Math Object Random Number Challenge – Two Numbers Solution

Math.random() question regarding {low input} and {high input}: What's the difference between no ' +1 ' and +1?

// Collect inputs from a user
let input = prompt('Please provide a low number:');
let input2 = prompt('Please provide a high number:');

// Convert each input to a number
input = parseInt(input);
input2 = parseInt(input2);

if (input && input2) {
  // Use Math.random() and the user's number to generate a random number

   // **MY ORIGINAL solution** -- no plus 1
   //const randNum = Math.floor(Math.random() * (input2 - input1)) + input;

   //  **VIDEO SOLUTION guidelines**
   const randNum = Math.floor(Math.random() * (input2 - input1 + 1)) + input;

  // Log a message displaying the random number generated between first and second num input
  console.log(`${randNum} is a random number between ${input} and ${input2}.`);
  // otherwise
} else {
  // Log error message
  console.log('Invalid number(s) input. Please try again.');
}

1 Answer

Steven Parker
Steven Parker
230,970 Points

Adding 1 to the range allows the result to be inclusive of the upper limit. Otherwise, it is exclusive of the limit.

So with the standard formula (+1), if you asked for a number between 10 and 20, it has an equal chance of being 20 as any other number.

But with your formula, when you ask for a number between 10 and 20, the largest number you could ever get back would be 19.