Math.random and Math.floor
In short: Math.random() returns a random number in JavaScript from 0 (inclusive) to 1 (exclusive). Math.floor(x) rounds down to the nearest whole number. Together they create integer random values.
In more detail: The random number is a decimal such as 0.7342. To get a number in a range you scale it with the size of the range and round down.
In detail
// integer from 0 to 5 (die minus 1)
const r = Math.floor(Math.random() * 6);
// die 1 to 6
const die = Math.floor(Math.random() * 6) + 1;
// range min..max (inclusive)
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;- floor, ceil, round, trunc:
floordown,ceilup,roundto nearest,trunccuts off decimals. For negative numbers floor and trunc differ (floor(-1.5)is -2,trunc(-1.5)is -1). - Not secure:
Math.random()is unsuitable for passwords and tokens, usecrypto.getRandomValuesthere, see Random numbers: pseudo-random and true random. - Other languages: see Random and rounding in many programming languages.
See also: Random values, Mathematical functions