Math.random() returns a random number in the range of 0 (inclusive) to 1 (exclusive).
// Returns a random number: Math.random(); |
Math.random() consistently returns a number that is less than 1. |
Combining Math.random() with Math.floor() can produce random integers.
JavaScript does not have a distinct integer type; instead, it uses numbers without decimals to represent integers. |
// Returns a random integer from 0 to 9: Math.floor(Math.random() * 10); |
// Returns a random integer from 0 to 10: Math.floor(Math.random() * 11); |
// Returns a random integer from 0 to 99: Math.floor(Math.random() * 100); |
// Returns a random integer from 0 to 100: Math.floor(Math.random() * 101); |
// Returns a random integer from 1 to 10: Math.floor(Math.random() * 10) + 1; |
// Returns a random integer from 1 to 100: Math.floor(Math.random() * 100) + 1; |
As illustrated in the examples above, it’s advisable to create a dedicated random function for generating random integers. This JavaScript function consistently returns a random number within the range of min (inclusive) and max (exclusive).
function getRndInteger(min, max) { return Math.floor(Math.random() * (max – min) ) + min; } |
This JavaScript function consistently returns a random number within the range of min and max, including both endpoints.
function getRndInteger(min, max) { return Math.floor(Math.random() * (max – min + 1) ) + min; } |