JavaScript ยท Chapter 26 of 55
JavaScript Random Numbers
`Math.random()` returns a pseudo-random floating point number between 0 (inclusive) and 1 (exclusive). Combine it with multiplication and `Math.floor()` to generate random integers within a range.
This technique is widely used for things like dice games, shuffling arrays, or picking a random item from a list.
Random integers
`Math.floor(Math.random() * 10)` gives a random whole number from 0 to 9. Add a minimum to shift the range.
Random array item
`arr[Math.floor(Math.random() * arr.length)]` picks a random element from any array.
Example 1 (javascript)
let dice = Math.floor(Math.random() * 6) + 1;
console.log(dice >= 1 && dice <= 6);Output
trueSimulates a six-sided die roll from 1 to 6.
Example 2 (javascript)
let colors = ["red", "green", "blue"];
let pick = colors[Math.floor(Math.random() * colors.length)];
console.log(colors.includes(pick));Output
truePicks a random element that is guaranteed to be in the array.
Key points
- Math.random() returns a number between 0 (inclusive) and 1 (exclusive).
- Multiply and floor to scale into an integer range.
- Add an offset to shift the minimum value.
- Math.random() is not cryptographically secure.
๐ก Note: For security-sensitive randomness (like tokens), use the Web Crypto API's crypto.getRandomValues() instead.
