iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Math

The Math object is a global namespace of math constants and functions. All members are static — you never call new Math().

Constants

ConstantValue
Math.PI~3.14159
Math.E~2.71828
Math.LN2 / Math.LN10Natural log of 2 / 10
Math.SQRT2√2

The functions you actually use

FunctionExample
Math.abs(x)Math.abs(-5) → 5
Math.round / floor / ceil / truncMath.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 / log10Natural / base-2 / base-10 log
Math.sin / cos / tanTrig (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);

Test yourself

Q1. Round 3.7 down to 3 with…
Q2. Math.PI ≈
Q3. Euclidean distance √(x² + y²) with…

Discussion

Loading…