JavaScript Random
In JavaScript, you can generate random numbers using the Math.random() method.
This method returns a floating-point, pseudo-random number in the range from 0 (inclusive) up to but not including 1 (exclusive). Here's how you can use it:
Example
let randomNumber = Math.random(); console.log(randomNumber); // Output will be a random number between 0 and 1 (exclusive)
To generate a random integer within a specific range, say between min (inclusive) and max (exclusive):
Example
function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive } let randomInRange = getRandomInt(5, 10); console.log(randomInRange); // Output will be a random integer between 5 (inclusive) and 10 (exclusive)
If you need a random integer within a specific range, you can use Math.floor() to round down the number obtained from Math.random() and then scale it to fit your range.
For example, to generate a random integer between 0 (inclusive) and 10 (exclusive):