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

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

Why Math.floor ( Math.random() * 6 ) + 1; works good but Math.floor ( Math.random() * 6 ) + 4; doesn't?

In this lesson we've got such a code: var number = Math.floor ( Math.random() * 6 ) + 1; - and this code draws numbers from 1 to 6... okay, everything's clear. But why this code: var number = Math.floor ( Math.random() * 6 ) + 4; doesn't draws numbers from 4 to 6... It gives me numbers like 8, 7, 9 etc...

4 Answers

Dmitry Polyakov
Dmitry Polyakov
4,989 Points

To get a numbers range starting and ending with some certain numbers that you want you need to use Math.floor(Math.random() * (max - min)) + min

max - is not included

For example:

Math.floor(Math.random() * (11 - 5)) + 5

You'll get numbers from 5 to 10 (11 won't be generated)

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

Now I understand this formula. Math.floor(Math.random() * (b)) + a; Where "a" is the lowest number, and "b" is how many numbers program takes into consideration after "a". I simply thought that a is the lowest number and b is the highest number...

Dmitry Polyakov
Dmitry Polyakov
4,989 Points

It should work. I just checked it. It generates numbers from 4 till 9

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

Well... it still gives me numbers from 4 to 9. Im using exactly this code: var number = Math.floor ( Math.random() * 6 ) + 4; document.write ( number );

And I know the solution. I know that if I'll write: var number = Math.floor ( Math.random() * ( 6 - 4 + 1 ) ) + 4; document.write ( number ); then I'll get numbers from 4 to 6... But I don't understand why this first solution doesn't work well.

Dmitry Polyakov
Dmitry Polyakov
4,989 Points

What result do you want to get?

Tomasz Grodzki
Tomasz Grodzki
8,130 Points

If code Math.floor ( Math.random() * 6 ) + 1 gives me number from 1 to 6... then why code Math.floor ( Math.random() * 6 ) + 4 doesnt give me a number from 4 to 6?