JavaScript Math - Random Method Explained
JavaScript Math - Random Method Explained
JavaScript
Math.random()
Method Explained
Random Method
The JavaScript Math.random() method is an excellent built-in method
Generating a random
floating point number
between 0 and 1
The Math.random() method will return a floating point (decimal)
number greater than or equal to 0 and less than (but never equal to) 1.
console.log(Math.random());
// 0.7069207248635578
console.log(Math.random());
// 0.765046694794209
console.log(Math.random());
// 0.14069121642698246
(Of course, the numbers returned will be different every time. This will
each pass.)
https://www.freecodecamp.org/news/javascript-math-random-method-explained/ 2/8
25/08/2020 JavaScript Math.random() Method Explained
To get a random number between a larger range multiply the result of M
Generating a random
floating point number
between 0 and a
specified max
Usually you do not need random numbers between 0 and 1 - you need
var x = Math.random()*10;
console.log(x);
// 4.133793901445541
https://www.freecodecamp.org/news/javascript-math-random-method-explained/ 3/8
25/08/2020 JavaScript Math.random() Method Explained
Generating a random
floating point number
within a range
If you need a random floating point number that ranges between two
console.log(x);
// 126.94014012699063
Generating a random
integer between 0 and
a max
https://www.freecodecamp.org/news/javascript-math-random-method-explained/ 4/8
25/08/2020 JavaScript Math.random() Method Explained
Often you need integers. To do this you will have to use some other
var x = Math.floor(Math.random()*10);
console.log(x);
// 7
ndom()*10 will never return exactly 10. This means that after rounding
Generating a random
integer between 1 and
a max
https://www.freecodecamp.org/news/javascript-math-random-method-explained/ 5/8
25/08/2020 JavaScript Math.random() Method Explained
If you need a random number with the minimum number being 1 (for
example picking a random day in January) you could use the Math.cei
l() method.
var x = Math.ceil(Math.random()*31);
console.log(x);
// 23
Another way would have been to use the previous function (using Mat
var x = Math.floor(Math.random()*31)+1;
console.log(x);
// 17
Generating a random
integer within a range
https://www.freecodecamp.org/news/javascript-math-random-method-explained/ 6/8
25/08/2020 JavaScript Math.random() Method Explained
integers. For example, if you are trying to pick raffle tickets and you
var x = Math.floor(Math.random()*(max-min+1)+min);
console.log(x);
//2509
How random is
Math.random()?
It may be pointed out that the number returned by Math.random() is a
number, that exhibits randomness over all scales and over all sizes of
ndom() is usually sufficient for the needs of nearly any program you
https://www.freecodecamp.org/news/javascript-math-random-method-explained/ 8/8