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

Bjørn Jakobsen
Bjørn Jakobsen
Front End Web Development Techdegree Student 8,205 Points

My solution with a second validation to check if the high number is higher than the low number

// Collect input from a user
const lowUserNumber = prompt('Please provide your lowest number.');
const highUserNumber = prompt('Please provide your highest number.');

// Convert the input to a number
const lowNumber = +lowUserNumber;
const highNumber = +highUserNumber;


if(lowNumber && highNumber ){
  if ( (highNumber > lowNumber) ) {
    // Use Math.random() and the user's number to generate a random number
    const randomNumber = Math.floor( Math.random() * (highNumber - lowNumber + 1) ) + lowNumber;

 // Create a message displaying the random number
    document.querySelector('main').innerHTML = `${randomNumber} is a random number betwwn ${lowUserNumber} and ${highUserNumber}`;
  } else {
    document.querySelector('main').innerHTML = `The second number has to be higher than the first. Try again.`

} else {
  document.querySelector('main').innerHTML = `You need to provide two numbers. Try again.`

1 Answer

Steven Parker
Steven Parker
216,891 Points

When posting code, use Markdown formatting to preserve the code's appearance and retain special symbols.

But a nice enhancement to the example program. You'll probably think of many ways to improve the examples in future lessons.