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

Please explain the *10 and +1 in this problem

When writing code to generate a random whole number between 1 and 10, why am I multiplying by 10 and then adding 1? It is working each time it is run, of course, I am just trying to understand why it is working. Thanks in advance!

var random = Math.floor(Math.random() *10)+1;

2 Answers

Math.random() generates a random number between 0 (inclusive), and 1 (exclusive)

Multiplying by ten makes the number between 0 (inclusive), and 10 (exclusive)

Taking the floor makes the number between 0 (inclusive) and 9 (inclusive)

Adding 1 makes the number between 1 (inclusive) and 10 (inclusive)

So it's a formula for generating a random number between 1 and 10

Thanks! You are awesome!