How to Generate Random Number in JavaScript: Simple Guide
Use
Math.random() to generate a random decimal number between 0 (inclusive) and 1 (exclusive). To get a random number in a specific range, multiply the result and adjust with addition, then use Math.floor() or Math.round() to get whole numbers.Syntax
The basic syntax to generate a random decimal number is Math.random(). It returns a number from 0 up to but not including 1.
To get a random integer in a range, use: Math.floor(Math.random() * (max - min + 1)) + min.
- Math.random(): generates a decimal between 0 and 1.
- Math.floor(): rounds down to the nearest whole number.
- max: the highest number you want.
- min: the lowest number you want.
javascript
Math.random() // To get a random integer between min and max (inclusive): Math.floor(Math.random() * (max - min + 1)) + min
Example
This example shows how to generate a random integer between 1 and 10 and print it.
javascript
const min = 1; const max = 10; const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min; console.log(randomNumber);
Output
7
Common Pitfalls
One common mistake is forgetting to add 1 when calculating the range, which causes the maximum number to never appear.
Another is using Math.round() which can bias the results unevenly.
javascript
// Wrong: max number never appears const wrongRandom = Math.floor(Math.random() * (max - min)) + min; // Right: includes max number const rightRandom = Math.floor(Math.random() * (max - min + 1)) + min;
Quick Reference
| Purpose | Code Snippet |
|---|---|
| Random decimal 0 to 1 | Math.random() |
| Random integer 0 to max | Math.floor(Math.random() * (max + 1)) |
| Random integer min to max | Math.floor(Math.random() * (max - min + 1)) + min |
Key Takeaways
Use Math.random() to get a decimal between 0 and 1.
Multiply and add to scale the random number to your desired range.
Use Math.floor() to get whole numbers without bias.
Always add 1 to the range calculation to include the max number.
Avoid Math.round() for random integers to prevent uneven distribution.