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

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
231,275 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!