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 trialDanish Arif
1,667 PointsWhy 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
Timothy Durward
3,242 PointsHello Danish, parseInt() interprets the argument as a string. Rule of thumb is to always Math.floor if that is your intention.
Timothy Durward
3,242 PointsTimothy Durward
3,242 PointsThis also explains the majority of of parseInt() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Marcus Parsons
15,719 PointsMarcus Parsons
15,719 PointsExactly, 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
8,401 PointsRafael Valera
8,401 Pointsis it posible to cast whatever Math.random() returns to a whole number?
Marcus Parsons
15,719 PointsMarcus Parsons
15,719 PointsThat'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.
Rafael Valera
8,401 PointsRafael Valera
8,401 PointsThanks 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
Marcus Parsons
15,719 PointsMarcus Parsons
15,719 PointsCheers, Rafael!