Rounding, Random, Min/Max, and the Usual Suspects
JavaScript Math
`Math` is a namespace of static methods and constants for numeric work — rounding, comparison, exponents, randomness.
What you'll learn
- Round and floor/ceil with the right method
- Generate random numbers in a range
- Find min/max across an array
Math isn’t a constructor — it’s a frozen object of static
functions and constants. You never new Math(). Just call
Math.something(...).
Rounding
| Method | Behavior |
|---|---|
Math.round(x) | Round to nearest. 0.5 rounds UP |
Math.floor(x) | Round DOWN to integer |
Math.ceil(x) | Round UP to integer |
Math.trunc(x) | Drop the fractional part (round toward zero) |
n.toFixed(d) | Format with d decimals — returns a STRING |
console.log(Math.round(2.5)); // 3
console.log(Math.round(-2.5)); // -2 (rounds toward +∞ on .5)
console.log(Math.floor(2.9)); // 2
console.log(Math.ceil(2.1)); // 3
console.log(Math.trunc(-2.9)); // -2 (NOT -3)
console.log((1.005).toFixed(2)); // "1.00" ← float-point gotcha ▶ Preview: console
Min, Max, Abs, Sign
console.log(Math.min(3, 1, 2)); // 1
console.log(Math.max(3, 1, 2)); // 3
console.log(Math.abs(-7)); // 7
console.log(Math.sign(-7)); // -1 (-1, 0, or 1) ▶ Preview: console
For an array, spread it:
const nums = [3, 1, 9, 4];
console.log(Math.max(...nums)); // 9 ▶ Preview: console
Powers, Roots, Logs
console.log(Math.pow(2, 8)); // 256 (or 2 ** 8)
console.log(Math.sqrt(81)); // 9
console.log(Math.cbrt(27)); // 3
console.log(Math.log2(1024)); // 10
console.log(Math.log10(1000)); // 3 ▶ Preview: console
** is the operator form of Math.pow and is usually what you’ll
reach for.
Random
Math.random() returns a number in [0, 1) (zero included, one
excluded).
// Random int in [min, max] inclusive
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randInt(1, 6)); // 1..6 — a die roll ▶ Preview: console
Constants Worth Knowing
| Constant | Value |
|---|---|
Math.PI | π |
Math.E | Euler’s number |
Math.LN2 | ln(2) |
Math.LN10 | ln(10) |
Trig (Briefly)
Angles are in radians, not degrees. Multiply by Math.PI / 180
to convert.
const deg = 90;
const rad = deg * Math.PI / 180;
console.log(Math.sin(rad)); // 1 Up Next
You’ve seen the language. The last stop is a quick tour of useful browser-platform APIs you’ll meet in real apps.
JavaScript Web APIs Tour →