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 – Solution

Danny Short
PLUS
Danny Short
Courses Plus Student 2,470 Points

Why does this always evaluate as false?

My Solution doesn't work with my if statement i used typeof to compare the type of my variable against the type number

// Collect input from a user
let userNumber = prompt('Choose a number?');

// Convert the input to a number

const highNumber = parseInt(userNumber);

if (typeof highNumber === Number) {
  // Use Math.random() and the user's number to generate a random number

  const randomNumber = (Math.random() * (highNumber) +1 );

  // Create a message displaying the random number

  console.log(`${parseInt(randomNumber)} is a random Number between 1 and ${highNumber}`);
} else {
  console.log(`That's not a number you trickster`);
}

2 Answers

Steven Parker
Steven Parker
229,732 Points

The "typeof" operator will return a string with the type in lower case:

if (typeof highNumber === "number") {

Also, "randomNumber" is already a number, you don't need to perform "parseInt" on it.

Danny Short
PLUS
Danny Short
Courses Plus Student 2,470 Points

I think I did the parse Int because random number is a float at that point & wanted it to be an int could use Math.floor in the original declaration instead

Steven Parker
Steven Parker
229,732 Points

Since "parseInt" is specifically for strings, an implicit coercion has to happen here. The use of "floor" is a much more conventional approach.