[JS] Generate a random number between Min and Max and exclude a specific number

Last updated on February 13, 2022 A Goodman Loading... One comment

Creating a random number is popular stuff in Javascript that has many use cases.

Image source: Pixabay

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);    

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:

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.

Notify of
1 Comment
Inline Feedbacks
View all comments
Ron Conner
Ron Conner
5 months ago

Suggestion: instead of rerolling from min to max whenever the roll is exclude, roll from min to max-1 and if the roll is >= exclude then add 1 to the roll. This ensures exclude is skipped without having to reroll.

Related Articles