This snippet generates a random integer between a specified minimum and maximum range (inclusive). It uses JavaScript's Math.random() function combined with Math.floor() for the random number generation.
// Define the range
const minNum = 1;
const maxNum = 100;
// Generate a random integer within the range
const answer = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;
// Output the random number
console.log(answer);-
Math.random():- Generates a random decimal number between 0 (inclusive) and 1 (exclusive).
-
Math.random() * (maxNum - minNum + 1):- Scales the random decimal to the size of the range.
-
Math.floor():- Rounds down to the nearest whole number, ensuring the result is an integer.
-
+ minNum:- Offsets the range to start at
minNum.
- Offsets the range to start at
If Math.random() generates 0.456, the calculation works as follows:
0.456 * (100 - 1 + 1) = 45.6Math.floor(45.6) = 4545 + 1 = 46
The result would be: 46.
This logic is helpful for:
- Random number games.
- Generating IDs within a specific range.
- Any functionality requiring a random integer within defined bounds.
After running the code, the generated random number will appear in the console.