JS Math
The Math object is a global namespace of math constants and functions. All members are static — you never call new Math().
Constants
| Constant | Value |
|---|---|
Math.PI | ~3.14159 |
Math.E | ~2.71828 |
Math.LN2 / Math.LN10 | Natural log of 2 / 10 |
Math.SQRT2 | √2 |
The functions you actually use
| Function | Example |
|---|---|
Math.abs(x) | Math.abs(-5) → 5 |
Math.round / floor / ceil / trunc | Math.floor(3.7) → 3 |
Math.min(...) / max(...) | Math.min(3, 1, 5) → 1 |
Math.pow(b, e) | Math.pow(2, 10) → 1024 (or 2 ** 10) |
Math.sqrt(x) / Math.cbrt(x) | Square / cube root |
Math.sign(x) | 1 / 0 / -1 |
Math.log / log2 / log10 | Natural / base-2 / base-10 log |
Math.sin / cos / tan | Trig (radians) |
Math.hypot(x, y) | Euclidean distance |
Common recipes
JS
// Round to 2 decimal places
Math.round(value * 100) / 100;
// Clamp between min and max
function clamp(x, min, max) { return Math.min(Math.max(x, min), max); }
// Max of an array (spread, but watch the stack on huge arrays)
Math.max(...nums);
// Distance between two points
Math.hypot(x2 - x1, y2 - y1);
// Map a value from one range to another
const mapped = (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
Tip: For huge arrays,
Math.max(...arr) can blow the call stack. Use arr.reduce((m, n) => Math.max(m, n), -Infinity) instead.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Math!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Pick the larger of x and y.
const bigger = Math.
(x, y);
Three letters.
Discussion
Loading…