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 Object-Oriented JavaScript (2015) Introduction to Methods Adding a Method to an Object

Craig Curtis
Craig Curtis
19,985 Points

Why did Mr. Chalkley use Math.floor(Math.random() * sides) + 1 instead of Math.ceil(Math.random * sides) ??

Shouldn't we write less code? Or is he (Mr. Chalkley) just showing the mechanics of Math.random() as being a float between 0 and 1?

2 Answers

Seth Kroger
Seth Kroger
56,412 Points

Math.random() can return 0 and Math.ceil(0) is 0. So the latter code will return a random number from 0 to sides instead of from 1 to sides like the former.

because math floor rounds down and you add the 1 to bring it up to the next integer because you rounded down.