Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create a random number between a range JavaScript
Our job is to create a function, say createRandom, that takes in two arguments and returns a pseudorandom number between the range (max exclusive).
Syntax
const createRandom = (min, max) => {
const diff = max - min;
const random = Math.random();
return Math.floor((random * diff) + min);
}
Example
const min = 3;
const max = 9;
const createRandom = (min, max) => {
const diff = max - min;
const random = Math.random();
return Math.floor((random * diff) + min);
}
console.log(createRandom(min, max));
console.log(createRandom(min, max));
console.log(createRandom(min, max));
6 4 8
How It Works
Understanding the algorithm:
- We take the difference of max and min to get the range size
- We create a random decimal between 0 and 1 using Math.random()
- Then we multiply the diff and random to produce random number between 0 and diff
- Then we add min to it to shift the range from [0, diff) to [min, max)
- Finally, Math.floor() converts the decimal to an integer
Alternative: Inclusive Range
To include the maximum value in the possible results:
const createRandomInclusive = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(createRandomInclusive(3, 9)); // Can output 9
console.log(createRandomInclusive(3, 9));
console.log(createRandomInclusive(3, 9));
9 5 3
Comparison
| Method | Range | Includes Max? |
|---|---|---|
| createRandom(3, 9) | 3, 4, 5, 6, 7, 8 | No |
| createRandomInclusive(3, 9) | 3, 4, 5, 6, 7, 8, 9 | Yes |
Conclusion
Use Math.random() with range calculation to generate numbers within bounds. Choose between exclusive or inclusive based on your needs.
Advertisements
