The Math Object
The arithmetic operators (+, -, *, /, %, **) handle everyday calculations, but real programs need rounding, square roots, randomness, and trigonometry. JavaScript bundles all of that into the built-in Math object. It is not a constructor — you never write new Math() — instead it is a namespace of static methods and constants you call directly, such as Math.round() or Math.PI. Everything operates on regular number values and runs identically in browsers and Node.js.
Rounding numbers
The four rounding methods each break ties and discard fractions differently. Math.round rounds to the nearest integer (with .5 always going up toward positive infinity), Math.floor rounds down, Math.ceil rounds up, and Math.trunc simply chops off the decimal part without rounding at all.
console.log(Math.round(4.5)); // ties round toward +Infinity
console.log(Math.round(-4.5));
console.log(Math.floor(4.9));
console.log(Math.ceil(4.1));
console.log(Math.trunc(-4.9));
Output:
5
-4
4
5
-4
| Method | Input 2.5 | Input -2.5 | Behavior |
|---|---|---|---|
Math.round | 3 | -2 | Nearest integer, .5 goes up |
Math.floor | 2 | -3 | Toward negative infinity |
Math.ceil | 3 | -2 | Toward positive infinity |
Math.trunc | 2 | -2 | Drops the fractional part |
Note the difference between
Math.floor(-2.5)(-3) andMath.trunc(-2.5)(-2). For negative numbersfloorandtruncdisagree, which is a classic source of off-by-one bugs.
To round to a fixed number of decimal places, scale up, round, then scale back down:
const roundTo = (value, decimals = 2) => {
const factor = 10 ** decimals;
return Math.round(value * factor) / factor;
};
console.log(roundTo(3.14159, 2));
console.log(roundTo(2.005, 2)); // floating-point caveat below
Output:
3.14
2
Because of binary floating-point representation,
2.005is stored as slightly less than2.005, so it rounds to2. For money, prefer integer cents or a decimal library — see Number precision.
Absolute value, min and max
Math.abs strips the sign from a number. Math.min and Math.max accept any number of arguments and return the smallest or largest. To use them on an array, spread it.
console.log(Math.abs(-7));
console.log(Math.min(3, 1, 4, 1, 5));
console.log(Math.max(3, 1, 4, 1, 5));
const scores = [88, 95, 72, 100, 64];
console.log(Math.max(...scores));
console.log(Math.min(...scores));
Output:
7
1
5
100
64
Calling
Math.max()with no arguments returns-Infinity, andMath.min()returnsInfinity. Spreading a huge array can also overflow the call stack — for very large datasets, usearray.reduce()instead.
Powers and roots
Math.pow(base, exponent) predates the ** operator and still works everywhere; the two are equivalent. Math.sqrt gives the square root and Math.cbrt the cube root. The square root of a negative number is NaN.
console.log(Math.pow(2, 10));
console.log(2 ** 10); // identical, preferred today
console.log(Math.sqrt(144));
console.log(Math.cbrt(27));
console.log(Math.sqrt(-1)); // NaN
// Distance between two points
const distance = (x1, y1, x2, y2) =>
Math.hypot(x2 - x1, y2 - y1);
console.log(distance(0, 0, 3, 4));
Output:
1024
1024
12
3
NaN
5
Math.hypot(a, b) computes Math.sqrt(a*a + b*b) while guarding against intermediate overflow, which makes it the right tool for distances and vector magnitudes.
Random numbers
Math.random() returns a floating-point number in the range [0, 1) — zero is possible, one is never returned. By itself that is rarely what you want, so wrap it in helpers to produce values in a range.
// Float in [min, max)
const randomFloat = (min, max) => Math.random() * (max - min) + min;
// Integer in [min, max] inclusive on both ends
const randomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
// Pick a random element
const pick = (arr) => arr[randomInt(0, arr.length - 1)];
console.log(randomInt(1, 6)); // a dice roll
console.log(pick(['rock', 'paper', 'scissors']));
Math.random()is not cryptographically secure. For tokens, passwords, or anything security-sensitive, usecrypto.getRandomValues()(browser) orcrypto.randomInt()(Node.js). See Random numbers.
Trigonometry for canvas and animation
The trig functions (sin, cos, tan, and their inverses asin, acos, atan, atan2) work in radians, not degrees. Convert with the ratio Math.PI / 180. These are essential for positioning points on a circle, rotating sprites, and computing angles between objects in canvas or game code.
const toRadians = (deg) => deg * (Math.PI / 180);
const toDegrees = (rad) => rad * (180 / Math.PI);
// Point on a circle of radius r at a given angle
const cx = 100, cy = 100, r = 50;
const angle = toRadians(45);
const x = cx + r * Math.cos(angle);
const y = cy + r * Math.sin(angle);
console.log(`${x.toFixed(2)}, ${y.toFixed(2)}`);
// Angle from one point to another (great for "look at" logic)
const heading = Math.atan2(200 - cy, 200 - cx);
console.log(toDegrees(heading).toFixed(1));
Output:
135.36, 135.36
45.0
Math.atan2(dy, dx) is preferable to Math.atan(dy / dx) because it inspects the signs of both arguments to return the correct angle across all four quadrants, and it safely handles dx === 0.
Handy constants
Math also exposes mathematical constants as read-only properties.
| Constant | Approx. value | Meaning |
|---|---|---|
Math.PI | 3.14159 | Ratio of circumference to diameter |
Math.E | 2.71828 | Euler’s number (natural log base) |
Math.SQRT2 | 1.41421 | Square root of 2 |
Math.LN2 | 0.69315 | Natural logarithm of 2 |
Best Practices
- Prefer the
**operator overMath.powfor readability; reach forMath.powonly when targeting very old environments. - Use
Math.hypotfor distances instead of hand-rollingMath.sqrt(a*a + b*b)to avoid overflow. - Remember that
Math.roundandMath.floordisagree on negative numbers — pickMath.truncwhen you literally want to drop decimals. - Always convert degrees to radians before calling trig functions, and reach for
Math.atan2overMath.atanfor angles. - Never use
Math.random()for security; use the Web Crypto or NodecryptoAPIs instead. - Spread arrays into
Math.min/Math.max, but switch toreducefor very large arrays to avoid call-stack limits.