JavaScript comes with a built-in toolbox called Math, packed with useful math functions. You use them by writing Math. followed by the tool's name.
Rounding numbers
console.log(Math.round(4.5));
console.log(Math.round(4.4));
console.log(Math.floor(4.9));
console.log(Math.ceil(4.1));
console.log(Math.trunc(-4.7));
It prints
5 4 4 5 -4
| Method | What it does | Memory trick |
|---|---|---|
Math.round(x) | Rounds to the nearest whole number | Normal rounding |
Math.floor(x) | Always rounds down | The floor is down below |
Math.ceil(x) | Always rounds up | The ceiling is up above |
Math.trunc(x) | Chops off the decimal part | "Truncate" means "cut short" |
Other handy tools
console.log(Math.max(4, 19, 7, 2));
console.log(Math.min(4, 19, 7, 2));
console.log(Math.abs(-15));
console.log(Math.sqrt(81));
console.log(Math.PI);
It prints
19 2 15 9 3.141592653589793
Math.max(...)andMath.min(...)find the biggest and smallest of any numbers you give them.Math.abs(x)gives the absolute value, which means it removes the minus sign. Useful for "how far apart are these two numbers?"Math.sqrt(x)gives the square root.Math.PIis the number π. (Note: no parentheses! It's a value, not an action.)
Random numbers
Now for the fun one. Math.random() gives you a random decimal number between 0 (included) and 1 (not included). Every time you call it, you get a different number:
console.log(Math.random());
console.log(Math.random());
Output
0.7341858224108491 0.0286427493216813
(Your numbers will be different. That's the whole point!)
A random decimal between 0 and 1 isn't very useful on its own. But with a bit of math, we can turn it into a random whole number in any range we like. Here's how to simulate rolling a six-sided die:
const roll = Math.floor(Math.random() * 6) + 1;
console.log(roll);
Let's walk through it, step by step:
Math.random()gives a number from0up to (but not including)1, like0.734.* 6stretches it to a number from0up to (but not including)6, like4.404.Math.floor(...)rounds down to a whole number from0to5, like4.+ 1shifts it to a number from1to6, like5. 🎲
To get a random whole number from 1 to max:
Math.floor(Math.random() * max) + 1
Want a number from 1 to 100? Use max = 100. A coin flip? Use max = 2 (and say 1 is heads, 2 is tails). Bookmark this page. You'll come back to this recipe again and again for games.