[JS] Generate a random number between Min and Max and exclude a specific number
( 27 Articles)
Creating a random number is popular stuff in Javascript that has many use cases.

This article shows you how to generate a random number between a minimum number (inclusive) and a maximum number (exclusive) and the random number you get will always be different from a given specific number.
The code:
const generateRandomBetween = (min, max, exclude) => {
let ranNum = Math.floor(Math.random() * (max - min)) + min;
if (ranNum === exclude) {
ranNum = generateRandomBetween(min, max, exclude);
}
return ranNum;
}
// Test
const x = generateRandomBetween(0, 5, 3);
console.log(x);
When you run the above code, you will get a random number of numbers 0, 1, 2, and 4. Both 5 (the maximum) and 3 are excluded.
Further reading:
- Calculate Variance and Standard Deviation in Javascript
- Best Libraries for Formatting Date and Time in React
- 2 Ways to Set Default Time Zone in Node.js
- Javascript: Capitalize the First Letter of Each Word (Title Case)
- Javascript: Set HTML lang attribute programmatically
- Using Rest Parameters in TypeScript Functions
I have made every effort to ensure that every piece of code in this article works properly, but I may have made some mistakes or omissions. If so, please send me an email: [email protected] or leave a comment to report errors.
Suggestion: instead of rerolling from
min
tomax
whenever the roll isexclude
, roll frommin
tomax-1
and if the roll is >=exclude
then add 1 to the roll. This ensuresexclude
is skipped without having to reroll.