Math and Random
Rounding and chance.
The Math object is a toolbox of maths functions. Rounding, square roots, the biggest of several numbers, and random numbers, for games and simulations.

- A toolbox of maths
- Rounding, roots, max
- Random numbers
Math tools
Round, floor, and ceil round to the nearest, down, and up. Sqrt is the square root, and max and min find the extremes. Math dot random gives a decimal from zero up to one. To get a whole number from one to six, like a die, multiply by six, take the floor, and add one. Run it.
console.log(Math.round(4.6), Math.floor(4.6), Math.ceil(4.2));
console.log(Math.sqrt(81), Math.max(3, 9, 2), Math.min(3, 9, 2));
console.log(Math.abs(-7), Math.PI.toFixed(4));
const roll = () => Math.floor(Math.random() * 6) + 1;
const rolls = Array.from({ length: 10 }, roll);
console.log("Rolls:", rolls.join(" "));5 4 5 9 9 2 7 3.1416 Rolls: 3 2 1 2 5 4 1 3 2 2
A note on random
Math dot random is fine for games and simple simulations. But it isn't safe for passwords or security tokens, because it can be predicted. For anything secret, use crypto dot random UUID, or crypto dot get random values. Array dot from, with a length, is a handy way to build arrays.
| key | value |
|---|---|
| round / floor / ceil | nearest, down, up |
| Math.random() | 0 up to 1 |
| Dice | floor(random × 6) + 1 |
| Security | use crypto instead |
Summary
The Math object rounds, finds extremes, and makes random numbers. Next, a new section, asynchronous JavaScript.
Key takeaways- Math.round / floor / ceil
- Math.max / min
- Math.random()