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
true

Simulates 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
true

Picks 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.

๐Ÿ“ Quick Quiz

1. What range does Math.random() return?

2. How do you get a random integer 0-9?

3. Is Math.random() cryptographically secure?