Take a look at the following function:
- minNum: This is the lowest value that should be returned.
- maxNum: This is the highest value that should be returned.
For example: If you wanted a random number between 1 and 10, you would set minNum to 1 and maxNum to 10. This would return a random integer within the range of 1-10.
Take a look at the following examples, which show the function being used.
In the code below, we generated a random number between 1 and 100:
//Between 1 and 100 var num = random_int(1, 100); alert('Random number was: ' + num);
As you can see, we set the first parameter (minNum) to 1 and the second parameter (maxNum) to 100. This means that our function will return a random number within the range of 1-100.
Generating a random number between 1 and 5:
//Random int between 1 and 5 var num = random_int(1, 5); alert('Random number was: ' + num);
A random integer between 1 and 1000:
//Random int between 1 and 1000 var num = random_int(1, 1000); alert('Random number was: ' + num);
As you can see, this function is pretty straight-forward and easy to use. Simply adjust the min and max values to suit your requirements.
NB: This function is not cryptographically secure, as it uses the Math.random() method. As a result, you should not use it for security features such as passwords, lottery results or pin codes.
Hopefully, you found this guide useful!
Related: Generating random numbers with PHP.