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

Solution Allows User Input of Zero and Gives Feedback as User Inputs Data (Asks for High Number First)

const inputHigh = prompt("Let's generate a random number. What do you want the largest number that can be generated to be?");

const numberHigh = parseInt(inputHigh);

if (!numberHigh && numberHigh !== +0) {
  alert('You need to provide a high number. Try again.'); // if numberHigh is false (no input or value is a string) and isn't zero, the program displays an alert and the program ends.*/
} else {

  const inputLow = prompt("What do you want the lowest number that can be generated to be?");

  const numberLow = parseInt(inputLow);

  if (numberLow || numberLow === +0) { // JavaScript treats a zero without a unary plus operator as a false value, so I included the numeric zero value (+0) in the condition using a logical OR operator.
    const randomNumber = Math.floor( Math.random() * (numberHigh - numberLow + 1) ) + numberLow;
    alert(`The number generated from ${numberLow.toLocaleString()} to ${numberHigh.toLocaleString()} is ${randomNumber.toLocaleString()}`);
   } else {
     alert("You need to provide a low number. Please try again.");
   }}

1 Answer

Steven Parker
Steven Parker
240,995 Points

It's normal for a 0 numeric value or empty string to evaluate as a false when taken as a Boolean, you don't need a sign when comparing a 0 to a number.

But to use logic to combine multiple comparisons, each comparison must be complete. So for your code to work as you intended, do this:

if (numberLow == 0 || numberLow == 0)   // the === comparator will also work