Generate random number between two numbers in JavaScript
Get a random floating-point number between min
(included) and max
(not included):
Get a random integer between min
and max
(both included):
Use randomFloat
for fractional values and randomInt
for integers within your desired interval.
Creating a reusable function
If you're generating random numbers regularly, you might want a reusable function. Here's one that generates a random integer:
This approach enhances readability and maintainability and reduces the probability of errors when repeating the formula in different parts of your code.
Cryptographically secure random numbers
Security matters. Math.random()
is not cryptographically secure. For applications where this is significant, use window.crypto.getRandomValues()
:
Note: the Web Cryptography API is your friend when you need quality randomness.
Shortcuts for rounding down
For truncating decimals, here are some shorter ways:
-
Bitwise OR (
|
) Method: Quick and condensed. Good for 32-bit numbers. -
Double NOT (
~~
) Method: Has the same result, but some developers find it more readable.
Both have use cases, but be aware they might be less clear to novice JavaScripters.
Handling edge cases
Couple of things to watch out for with random number generation:
-
Negative ranges: Ensure your function also gracefully handles negative ranges.
-
Large intervals: Remember the safe limit for JS numbers (
Number.MAX_SAFE_INTEGER
). TherandomInt()
is not built for an astronomically large range.
Validating randomness
It's crucial to verify that your random numbers are really random:
- Test distinct ranges and run them multiple times. Are the numbers uniformly distributed?
- Use online tools to analyze your random outputs – http://random.org/analysis/ is one.
- Verify your function's ranges in sandbox environments – try using https://code.labstack.com/xObK_c4M.
Efficiency matters
When generating many random values at once, store the random base in a variable to avoid repeated calls:
But remember, doing this might impact the randomness of your result. It's useful in mathematical procedures that depend on the same base value.
Was this article helpful?