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 Basics (Retired) Working With Numbers Create a random number

Why not just use parseInt(Math.random()*6) + 1; ?

Am I missing something, or is it simple to just use parseInt(Math.random()*6) + 1;

Instead of, say, Math.Floor() or Math.Round() ...

Perhaps those are all good solutions, but they decided to go that route for the video? Hopefully someone with more Javascript knowledge can chime in.

1 Answer

Hello Danish, parseInt() interprets the argument as a string. Rule of thumb is to always Math.floor if that is your intention.

Exactly, Timothy. parseInt() is used to parse integers from strings. From the MDN, "If string is not a string [in reference to the first argument of parseInt()], then it is converted to one." So, what that means is that if you pass in numbers into parseInt, it will do this conversion: number -> string -> number. Math.floor(), however, doesn't have to do all of that type conversion for this statement because it only generates numbers and so, it is much faster. It just strips away the decimal points from whatever number it receives.

Rafael Valera
Rafael Valera
8,401 Points

is it posible to cast whatever Math.random() returns to a whole number?

That's the reason we use Math.floor(), which is to make it a whole number. Math.random() only returns values between 0 - 0.9999... which means that you have to use multiplication in order to get a higher maximum range out of Math.random(), use addition and subtraction to modify the minimum and maximum ranges and then use Math.floor() to chop off the decimal points and make the number a whole number. i.e.

//returns 1 of 10 possible numbers, 0-9
Math.floor(Math.random() * 10);
Rafael Valera
Rafael Valera
8,401 Points

Thanks for your reply, Marcus. There is this typecasting feature in Java which I was wondering if JS could support too.. But I'll stick then with floor() function. Greetings

Cheers, Rafael!