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

Updated: February 20, 2023 By: Khue Post a comment

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) but 3 will always be excluded.