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

The result is the same but my code is different. Is my code ok?

const inputHigh = prompt("Please enter a high number");
const inputLow = prompt("Please enter a low number");

const highNumber = parseInt(inputHigh); 
const lowNumber = parseInt(inputLow);

if (highNumber && lowNumber){
 const randomNumber = Math.floor(Math.random () * highNumber) +1; 
 console.log(`${randomNumber} is a random number between ${lowNumber} and ${highNumber}.`);
} else {
  console.log("You must enter two numbers. Please try again.");
}

1 Answer

You might want to use your lowNumber variable in the randomNumber calculation. In the line const randomNumber = Math.floor(Math.random () * highNumber) +1;, if lowNumber is 100 and highNumber is 101, your formula for randomNumber would allow any integer from 1 to the value of highNumber inclusive, which would be from 1 to 101 inclusive. Since 1 is less than the value of lowNumber in this case, there is no guarantee that your random number will be greater than or equal to the value of lowNumber.

In the line if (highNumber && lowNumber){, if either highNumber or lowNumber are equal to 0, the expression evaluates to false.