Cookie Consent by Free Privacy Policy Generator

Random Number Generator in JavaScript

Generating random numbers in JavaScript is pretty straightforward, but doing it properly means understanding how the Math.random() function works.

If you need a number within a specific range, you cannot just call Math.random() and expect it to play nice. You have to scale it, adjust for the min and max, and make sure it returns whole numbers if that is what you are after.

Code:
function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Example usage
let randomNumber = getRandomNumber(1, 100); // Generates a number between 1 and 100
console.log("Random Number:", randomNumber);
 
Back
Top