Get Random Integer in Javascript

In Javascript sometime you need a Random Integer. Here is best way to get Random Integer number in Javascript.

 

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Test the function:

console.log("Random 1", getRandomInt(1,100));
console.log("Random 2", getRandomInt(1,100));
console.log("Random 3", getRandomInt(1,100));
console.log("Random 4", getRandomInt(1,100));
console.log("Random 5", getRandomInt(1,100));

Output:

Random 1 5
Random 2 68
Random 3 96
Random 4 81
Random 5 9


Keywords: