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 Basics (Retired) Making Decisions with Conditional Statements Build a Random Number Guessing Game

Rich TheDon
Rich TheDon
1,996 Points

Hey! Dave said we should use parseInt() because prompt() is always a string. I have used Math.floor and it's working.

Is there a problem with using Math.floor()? What do you think?

Rich TheDon
Rich TheDon
1,996 Points
var randomNumber = (Math.floor(Math.random() * 6) + 1);
var guess = prompt("I am thinking of a number between 1 and 6. What is it?");

if (Math.floor(guess) === randomNumber) {
  alert("You are right!");
} else {
  alert("False!");
} 
Antti Lylander
Antti Lylander
9,674 Points

It seems that Math.floor() converts it's input to a number by itself. I just wonder why anyone would input a decimal in the prompt, i.e. why do you use Math.floor with guess in your conditional.

var randomNumber = (Math.floor(Math.random() * 6) + 1);
console.log(randomNumber + " " + typeof randomNumber)

var guess = prompt("I am thinking of a number between 1 and 6. What is it?");

console.log(guess + " " + typeof guess)

if (guess === randomNumber) {

  alert("You are right!");
  } else { alert("False!"); }

Try the above code ans open console and you'll see that variable quess is a string and randomNumber is a number.

3 Answers

Matthew Lang
Matthew Lang
13,471 Points

JavaScript is a language which is "loosely typed", meaning it doesn't bother with data types too much. It does conversions automatically, for example:

let sum = "5" + 5;
// sum = 10

JavaScript converts the string to an integer in order to complete the calculation. This is why your Math.floor() function works on a string, too.

TypeScript on the other hand is a strict syntactical superset of JavaScript, which adds static typing. TypeScript transpiles into plain JavaScript. Read more about TypeScript here: https://www.typescriptlang.org/

tomd
tomd
16,701 Points

Math.floor is used for rounding down. While it does work, It is bad practice to use it for converting strings to numbers.

parseInt can also do things like this.

console.log(parseInt('100px'));  // 100
Rich TheDon
Rich TheDon
1,996 Points

Thanks for your replies. I don't think that it's odd to input a decimal if you get asked to write a number. This was the reason for me to use Math.floor().