Random in JavaScript
Math.random()
Math.random()
Returns a random number between 0 (inclusive) and 1 (exclusive):
Example
Math.random(); // Returns a random number
Math.random()
Always returns a number less than 1.
JavaScript Random Integer
Math.random()
With Math.floor()
Used together to return a random integer.
Example
Math.floor(Math.random() * 10); // Returns a number between 0 and 9
Example
Math.floor(Math.random() * 11); // Returns a number between 0 and 10
Example
Math.floor(Math.random() * 100); // Returns a number between 0 and 99
Example
Math.floor(Math.random() * 101); // Returns a number between 0 and 100
Example
Math.floor(Math.random() * 10) + 1; // Returns a number between 1 and 10
Example
Math.floor(Math.random() * 100) + 1; // Returns a number between 1 and 100
An appropriate random function
As you can see from the example above, it is a good idea to create a random function to generate all random integers.
This JavaScript function always returns a number between min
and max
between (exclusive):
Example
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min)) + min; }
This JavaScript function always returns a number between min
and max
between (inclusive):
Example
function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }