Basics
The Math object
Ready-made maths functions: larger and smaller, absolute value, sign, random numbers, rounding.
Why it exists
Some calculations come up in every other program: find the larger, take the absolute value, get a random number, round. Writing them from scratch each time means extra lines and extra bugs. Math is a built-in "toolbox" available in any JavaScript, no libraries needed.
Where it's used
- Limiting a value:
Math.min(Math.max(value, 0), 100). - A difference without a sign:
Math.abs(a - b)— how much the price changed. - Randomness: shuffle questions, pick a winner, generate a colour.
- Rounding: Math.round, Math.floor, Math.ceil.
Syntax
Math.max(a, b, …)
Math.min(a, b, …)
Math.abs(x)
Math.sign(x)
Math.random()Examples
Math.max(3, 9, 4); // → 9const prices = [120, 80, 450];
Math.max(...prices); // → 450
Math.min(...prices); // → 80Math.abs(-7); // → 7
Math.sign(-7); // → -1const dice = Math.floor(Math.random() * 6) + 1;
dice >= 1 && dice <= 6; // → trueResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Math isn't a function or a class but a plain object with function properties and constants (Math.PI). You don't create it: Math.max(…) is called directly.
Math.max(...)andMath.min(...)take any number of numbers and return the largest or smallest. An array is passed with spread:Math.max(...prices).Math.abs(x)— the absolute value: the number without its sign.Math.sign(x)— the sign:1,-1or0.Math.random()— a random fraction from 0 (inclusive) to 1 (exclusive).- Math.round, Math.floor, Math.ceil,
Math.trunc— rounding (see the separate entry).
If any argument can't be turned into a number, the result is NaN.
Traps
How it differs from…
- The ternary operator
? : a > b ? a : bis the same asMath.max(a, b), but only for two numbers.Math.maxis shorter and takes any number of them.- Rounding:
Math.round,floor,ceil,toFixed The rounding functions live in
Mathtoo, but they have their own subtleties — they have a separate entry.
When to pick something else
For money and exact fractions, Math won't save you from binary-fraction inaccuracy — count in cents (whole numbers). For huge arrays, Math.max(...arr) can fail on the argument limit (hundreds of thousands of items) — use a loop or reduce then.