Generate Random Whole Numbers with JavaScript

Posted by

Random numbers are an important part of many programming applications. JavaScript provides a built-in function for generating random numbers, Math.random(). The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.

Generating Random Whole Numbers

To generate a random whole number, use the following syntax:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

Math.floor(Math.random() * (max - min + 1)) + min

[/dm_code_snippet]

Where the parameters are:

  • min: The minimum value to return (inclusive).
  • max: The maximum value to return (inclusive).

Example

Below is a code example which will generate a random whole number between 1 and 10 (inclusive):

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let randomNumber = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
console.log(randomNumber);

[/dm_code_snippet]

Note: You could also use the Math.ceil() function to round the number up instead of down.

Limitations

Be aware that the Math.random() function is not cryptographically secure, and should not be used to generate random numbers for security or cryptography-related purposes.

Conclusion

In this tutorial, we have demonstrated how to generate random whole numbers using JavaScript’s Math.random() function. We have also discussed its limitations and why it should not be used for security-related purposes. We hope this tutorial has been helpful.