Generate random number between two numbers in JavaScript
function randomIntFromInterval(min, max) { // min and max included return Math.floor(Math.random() * (max - min + 1) + min)}const rndInt = randomIntFromInterval(1, 6)console.log(rndInt)
What it does "extra" is it allows random intervals that do not start with 1.So you can get a random number from 10 to 15 for example. Flexibility.
Important
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
const rndInt = Math.floor(Math.random() * 6) + 1 console.log(rndInt)
Where:
- 1 is the start number
- 6 is the number of possible results (1 + start (6) - end (1))
Math.random()
Returns an integer random number between min (included) and max (included):
function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min;}
Or any random number between min (included) and max (not included):
function randomNumber(min, max) { return Math.random() * (max - min) + min;}
Useful examples (integers):
// 0 -> 10Math.floor(Math.random() * 11);// 1 -> 10Math.floor(Math.random() * 10) + 1;// 5 -> 20Math.floor(Math.random() * 16) + 5;// -10 -> (-2)Math.floor(Math.random() * 9) - 10;
** And always nice to be reminded (Mozilla):
Math.random() does not provide cryptographically secure randomnumbers. Do not use them for anything related to security. Use the WebCrypto API instead, and more precisely thewindow.crypto.getRandomValues() method.