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

Dave, can Math.random() yield 1? If it can, then we might get 7 from Math.floor(Math.random()*6) + 1 right?

I hope some one can help me clarify this, thanks in advance!

5 Answers

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive). The floor() method rounds a number downwards to the nearest integer, and returns the result.

So when you create random number, you will receive value 0-1. Then you need to multiply on 7 and then add 1 (if you want random number 0-7), because floor will rounds a number downwards.

Ferdinand Pretorius
Ferdinand Pretorius
18,705 Points

Hi Wuen Han Lee,

Math.random will return a floating-point random number between 0 and 1 , but NOT including 1 itself.

Sergey Podgornyy is correct.

Ok, I found the answer :" // Returns a random number between 0 (inclusive) and 1 (exclusive)"

I would suggest playing around with Math.random. there is a lot of fun things you can do with it. I would first suggest playing with rgb colors! See if you can make a div change colors by using the math.random and the CSS transition property. Or make multiple divs with different colors. There is a lot you can do with it.

Thanks Sergey, Ferdinand and Jacob for the prompt replies. You guys are amazing!