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

Guido 't Hooft
Guido 't Hooft
8,466 Points

Can i use Math.floor(Math.random()* 6 + 1); instead of Math.floor(Math.random()* 6) + 1;? It both does the same thing.

Can i use Math.floor(Math.random()* 6 + 1); instead of Math.floor(Math.random()* 6) + 1;? It both does the same thing.

Just want to know if one is better then the other?

Guido

3 Answers

Steven Parker
Steven Parker
216,150 Points

They both do exactly the same thing, because the "floor" function only affects the fractional part of a number. So you can add whole numbers before or after using "floor" and the result will be the same.

So the only possible advantage to either would be readability. I think the 2nd example is slightly better in that regard but I admit it's purely a personal judgement call.

I'm not sure but think Math.floor(Math.random()* 6) + 1; is better because then he first makes a number from 0 to 0.9 in brackets and then * 6 do before he +1 does. I think in the sense of calculation rules. But I can be wrong.

Guido 't Hooft
Guido 't Hooft
8,466 Points

Oke great! Thanks for your answers!