[JS] Generate a random number between “min” and “max” and exclude a specific number

February 17, 2020 Goodman Loading... Post a comment

This article will show you how to generate a random number between a minimum number and a max number 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);     

Create a random number is popular stuff in Javascript that used in many cases.

avatar

Related Articles