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 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,403 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.