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

Last updated on February 13, 2022 A Goodman Loading... Post a 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);    
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:

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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles