JS Math
JS Math
The Math object provides mathematical constants and functions. It is not a constructor, so you use it directly (e.g., Math.round()).
console.log(Math.PI); console.log(Math.E);
Common Math Methods
These are the most used Math methods in everyday JavaScript.
console.log(Math.abs(-10)); // 10 console.log(Math.sign(-10)); // -1 console.log(Math.pow(2, 3)); // 8 console.log(2 ** 3); // 8 (operator alternative) console.log(Math.sqrt(64)); // 8 console.log(Math.min(5, 1, 9)); // 1 console.log(Math.max(5, 1, 9)); // 9
Rounding
Rounding is common when working with UI, prices, and calculated values.
console.log(Math.round(4.6)); // 5 console.log(Math.round(4.4)); // 4 console.log(Math.floor(4.9)); // 4 console.log(Math.ceil(4.1)); // 5 console.log(Math.trunc(4.9)); // 4 console.log(Math.trunc(-4.9)); // -4
Clamp (Modern Pattern)
Clamping keeps a number inside a min/max range.
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
console.log(clamp(120, 0, 100)); // 100
console.log(clamp(-5, 0, 100)); // 0
JS Math Random
Math.random() returns a floating-point number between 0 (inclusive) and 1 (exclusive).
console.log(Math.random());
Random integer in a range (inclusive):
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6)); // dice
Security Note (Important)
Math.random() is not cryptographically secure. Do not use it for passwords, tokens, or security-sensitive values.
For stronger random values in the browser, use crypto.getRandomValues().
const bytes = new Uint8Array(8); crypto.getRandomValues(bytes); console.log(bytes);
JS Math Reference
The Math reference includes constants (PI, E) and methods for rounding, trigonometry, powers, logarithms, and more.
Next Step
Continue with JS RegExp to learn pattern matching and text search in JavaScript.