Math.random and Math.min/max
Learn to generate random numbers and use Math.min/Math.max for bounds.
Math.random
Math.random() returns a random decimal between 0 (inclusive) and 1 (exclusive) on each call. So the result can be 0 but never 1.
This range is too narrow; most of the time you want a specific integer range. You combine it with Math.floor. For a dice roll:
const dice = Math.floor(Math.random() * 6) + 1;Here Math.random() * 6 gives a value between 0 and 5.999...; Math.floor drops it to the 0-5 range; finally + 1 shifts it to 1-6.
Math.min and Math.max
Math.min returns the smallest of the given numbers and Math.max returns the largest. Both accept as many arguments as you want.
For example you can find the highest and lowest score in a class:
const highest = Math.max(65, 82, 91, 78);
const lowest = Math.min(65, 82, 91, 78);Here highest becomes 91 and lowest becomes 65. These methods are shorter than writing the comparisons yourself.
Exercise Roll three dice, find the lowest
Roll a dice three times: assign Math.floor(Math.random() * 6) + 1 to roll1, roll2 and roll3. Then use Math.min to put the smallest roll into lowest. Log lowest with console.log.
Show example solution
const roll1 = Math.floor(Math.random() * 6) + 1;
const roll2 = Math.floor(Math.random() * 6) + 1;
const roll3 = Math.floor(Math.random() * 6) + 1;
const lowest = Math.min(roll1, roll2, roll3);
console.log(lowest);
Test yourself
-
What range does Math.random() return?
- 0 (inclusive) to 1 (exclusive)
- 0 (exclusive) to 1 (inclusive)
- 1 to 10
- A random integer
Show answer
0 (inclusive) to 1 (exclusive) — Correct. Math.random can return 0 but never 1; the upper bound is exclusive.
-
Complete the dice roll (1-6)
const dice = Math.floor(Math.random() * 6) + ____;Show answer
const dice = Math.floor(Math.random() * 6) + 1; -
Match each method to its job
- Math.random
- 0 (incl.) to 1 (excl.)
- Math.min
- Smallest of arguments
- Math.max
- Largest of arguments
- Math.floor
- Down to whole number
-
What does Math.max(3, 7, 2) return?
console.log(Math.max(3, 7, 2));- 3
- 2
- 7
- 12
Show answer
7 — Correct. Math.max returns the largest argument; among 3, 7 and 2 the largest is 7.