Math.random()
method
Returns a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive).
Syntax
Math.random()
Example
javascript
Math.random(); // e.g. 0.7364921...
// Random integer between 1 and 10
Math.floor(Math.random() * 10) + 1;
// Random integer between min and max (inclusive)
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randInt(1, 6)); // dice roll
// Shuffle array
const arr = [1,2,3,4,5];
arr.sort(() => Math.random() - 0.5);