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

Random Numbers in JavaScript Math.random() at the Mozilla Developer Network

why random to six,why not to seven and Up?

or is it because he multiplied by 6?

help with this please!,and thanks in advance.

If you want a number higher than 6 the yes you can just replace 6 with a different number. For example

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

this would produce a number between 1 & 10

1 Answer

Hi wilton,

Math.random() returns a floating point number from 0 up to but not including 1. For example:

> Math.random()
0.2625259844878184
> Math.random()
0.06513541210374607
> Math.random()
0.5629554153276711

So that is great if you want a decimal number between 0 and 1, but normally you will want a larger number. To do this you can multiply Math.random() by a number. If we wanted numbers between 0 & up to but not including 100:

> Math.random() * 100
26.25259844878184
> Math.random() * 100
6.513541210374607
> Math.random() * 100
56.29554153276711

Often you will want a whole number, for that we can use Math.floor() which will strip off the numbers after the decimal:

> Math.floor( Math.random() * 100 )
26
> Math.floor( Math.random() * 100 )
6
> Math.floor( Math.random() * 100 )
56

Math.floor( Math.random() * 100 ) will return the numbers 0,1,2,3,4,5 ...... 97,98,99.

If you wanted numbers between 1 & 100 then you would need to + 1. So it becomes

Math.floor( Math.random() * 100 ) + 1

In the video Dave just used 6 as an example, but you can use what ever number you wanted.