00 Votes

JavaScript: Create random numbers

Tip by NetLabel | Last update on 2020-02-05 | Created on 2012-05-23

With this tiny function, you get a random number in JavaScript:

function RandomNumber(upperLimit) {
   return Math.floor(Math.random()*upperLimit);
}
 
// Example of a call
var x = RandomNumber(11);
alert(x); // Number between 0 and 10

We call the function RandomNumber() with a parameter, that indicates the upper limit of the generated numbers. The function then produces numbers from 0 to a value less than the upper limit.

Therefore, if we call the function with RandomNumber(3), the function will give us one of the numbers 0, 1 or 2.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

PHP: Rounding Numbers

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.