You are currently viewing How to Use Math random() Function in JavaScript

How to Use Math random() Function in JavaScript

 MathRandom Function

In this article, we will see how to use math random function in javascript. It is one of the essential functions in JavaScript. Math.random() function returns the value between 0 < 1.

Ex:

document.write(Math.random());

Whenever you reload, this function gives a random number between 0 to 1 in decimal.
If you want to random number between 1 to 10 in decimal, we need to put “* 10” inside the random() function. But we can’t get 10.
Ex:

document.write(Math.random() * 10);

If you want to have a random number in an integer between 0 to 10, we need to use “Math.trunc(Math.random()*10)”.

Ex:

document.write(Math.trunc(Math.random()*10))

 

Leave a Reply