Math is not a class and is never instantiated. It is a toolbox left within reach, whose functions you call directly. On an ordinary web project, four or five of them cover every need.
The rest are worth knowing by name only: logarithms, trigonometry, roots. You look them up the day you need one, you do not memorize them.
Definition
Math is a built-in object exposing mathematical constants and functions. All its properties are static: you write Math.round(x), never new Math(), and the new operator actually throws on it.
console.log(Math.round(2.5)); // 3
console.log(Math.floor(2.9)); // 2, downward
console.log(Math.ceil(2.1)); // 3, upward
console.log(Math.trunc(-2.7)); // -2, drops the decimal part
console.log(Math.max(3, 9, 1)); // 9
console.log(Math.abs(-4)); // 4The four ways to round
They look alike and disagree on negative numbers, which is the most common source of mistakes.
| Function | On 2.5 | On -1.5 | Behavior |
|---|---|---|---|
Math.round | 3 | -1 | Nearest, halves go up |
Math.floor | 2 | -2 | Always downward |
Math.ceil | 3 | -1 | Always upward |
Math.trunc | 2 | -1 | Removes the decimal part |
Math.round(-1.5) is -1 and not -2, because the rule is "upward" rather than "toward the larger absolute value". On durations or negative balances, this is exactly the kind of detail that shifts a total.
These functions return a number, unlike toFixed which returns a string. To round to two decimals and stay numeric: Math.round(x * 100) / 100.
Random numbers
Math.random() returns a decimal between 0 inclusive and 1 exclusive. Every draw is built from there.
// An integer between 1 and 6
const die = Math.floor(Math.random() * 6) + 1;
// A random element from an array
const options = ["a", "b", "c"];
const pick = options[Math.floor(Math.random() * options.length)];
console.log(die, pick);The Math.floor is essential: without it the index would be fractional and the array would return undefined. Note also that this draw is not cryptographic. For a security token you need crypto.randomUUID() or crypto.getRandomValues().
Frequently asked questions
How do I find the maximum of an array?
Math.max expects separate arguments, not a list. So it has to be spread out with Spread (...): Math.max(...values). Be careful on an empty array, where the call returns -Infinity, which goes unnoticed until some display becomes inconsistent.
Why is my two-decimal rounding sometimes wrong?
Because the starting number is already inexact. Math.round(1.005 * 100) / 100 gives 1 rather than 1.01, since 1.005 * 100 is actually a little under 100.5. The Number entry explains this floating point limit and the workaround, which is to work in whole numbers.
Is there an operator for powers?
Yes, ** arrived in 2016 and does the same thing as Math.pow: 2 ** 10 and Math.pow(2, 10) both equal 1024. The operator reads better inside a formula, the function stays useful when the power is passed as an argument to something else.