JavaScript Fundamentals
JavaScript Math Object: Complete Reference Guide
Master the JavaScript Math object. Learn mathematical operations, constants, methods, and practical applications for calculations.
By JavaScriptDoc Team•
mathjavascriptcalculationsnumbersmathematics
JavaScript Math Object: Complete Reference Guide
The Math object in JavaScript provides mathematical constants and functions. It's a built-in object that has properties and methods for mathematical operations.
Math Constants
The Math object provides several useful mathematical constants.
// Mathematical constants
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045 (Euler's number)
console.log(Math.LN2); // 0.6931471805599453 (Natural log of 2)
console.log(Math.LN10); // 2.302585092994046 (Natural log of 10)
console.log(Math.LOG2E); // 1.4426950408889634 (Log base 2 of E)
console.log(Math.LOG10E); // 0.4342944819032518 (Log base 10 of E)
console.log(Math.SQRT1_2); // 0.7071067811865476 (Square root of 1/2)
console.log(Math.SQRT2); // 1.4142135623730951 (Square root of 2)
// Using constants in calculations
const circleArea = Math.PI * Math.pow(radius, 2);
const circleCircumference = 2 * Math.PI * radius;
// Degrees to radians conversion
function degreesToRadians(degrees) {
return degrees * (Math.PI / 180);
}
function radiansToDegrees(radians) {
return radians * (180 / Math.PI);
}
Rounding Methods
Basic Rounding
// Math.round() - rounds to nearest integer
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.round(-4.5)); // -4 (rounds towards positive infinity)
// Math.floor() - rounds down
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(4.1)); // 4
console.log(Math.floor(-4.1)); // -5
// Math.ceil() - rounds up
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(4.9)); // 5
console.log(Math.ceil(-4.9)); // -4
// Math.trunc() - removes decimal part
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
console.log(Math.trunc(0.123)); // 0
Custom Rounding Functions
// Round to specific decimal places
function roundToDecimal(num, decimals) {
const factor = Math.pow(10, decimals);
return Math.round(num * factor) / factor;
}
console.log(roundToDecimal(3.14159, 2)); // 3.14
console.log(roundToDecimal(3.14159, 4)); // 3.1416
// Round to nearest multiple
function roundToNearest(num, multiple) {
return Math.round(num / multiple) * multiple;
}
console.log(roundToNearest(27, 5)); // 25
console.log(roundToNearest(28, 5)); // 30
// Financial rounding (banker's rounding)
function bankersRound(num) {
const rounded = Math.round(num);
if (Math.abs(num - rounded) === 0.5) {
return rounded % 2 === 0 ? rounded : rounded - 1;
}
return rounded;
}
console.log(bankersRound(2.5)); // 2 (even)
console.log(bankersRound(3.5)); // 4 (even)
Power and Root Functions
// Math.pow() - exponentiation
console.log(Math.pow(2, 3)); // 8 (2^3)
console.log(Math.pow(4, 0.5)); // 2 (square root)
console.log(Math.pow(27, 1 / 3)); // 3 (cube root)
// ES2016 exponentiation operator
console.log(2 ** 3); // 8
console.log(4 ** 0.5); // 2
// Math.sqrt() - square root
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(2)); // 1.4142135623730951
console.log(Math.sqrt(-1)); // NaN
// Math.cbrt() - cube root
console.log(Math.cbrt(27)); // 3
console.log(Math.cbrt(-8)); // -2
console.log(Math.cbrt(1)); // 1
// Math.hypot() - Euclidean distance
console.log(Math.hypot(3, 4)); // 5 (3² + 4² = 25, √25 = 5)
console.log(Math.hypot(3, 4, 5)); // 7.0710678118654755
// Custom root functions
function nthRoot(num, n) {
return Math.pow(num, 1 / n);
}
console.log(nthRoot(16, 4)); // 2 (4th root of 16)
Logarithmic Functions
// Math.log() - natural logarithm (base e)
console.log(Math.log(Math.E)); // 1
console.log(Math.log(10)); // 2.302585092994046
console.log(Math.log(1)); // 0
// Math.log10() - base 10 logarithm
console.log(Math.log10(10)); // 1
console.log(Math.log10(100)); // 2
console.log(Math.log10(1000)); // 3
// Math.log2() - base 2 logarithm
console.log(Math.log2(2)); // 1
console.log(Math.log2(8)); // 3
console.log(Math.log2(1024)); // 10
// Math.log1p() - log(1 + x)
console.log(Math.log1p(0)); // 0
console.log(Math.log1p(1)); // 0.6931471805599453
// Custom logarithm base
function logBase(num, base) {
return Math.log(num) / Math.log(base);
}
console.log(logBase(8, 2)); // 3
console.log(logBase(81, 3)); // 4
// Math.exp() - e^x
console.log(Math.exp(1)); // 2.718281828459045 (e)
console.log(Math.exp(0)); // 1
// Math.expm1() - e^x - 1
console.log(Math.expm1(0)); // 0
console.log(Math.expm1(1)); // 1.718281828459045
Trigonometric Functions
Basic Trigonometry
// Angles in radians
const angle = Math.PI / 4; // 45 degrees
// Basic trig functions
console.log(Math.sin(angle)); // 0.7071067811865476
console.log(Math.cos(angle)); // 0.7071067811865476
console.log(Math.tan(angle)); // 0.9999999999999999 (≈1)
// Common angles
console.log(Math.sin(0)); // 0
console.log(Math.sin(Math.PI / 2)); // 1
console.log(Math.cos(0)); // 1
console.log(Math.cos(Math.PI)); // -1
// Inverse trig functions
console.log(Math.asin(0.5)); // 0.5235987755982989 (30° in radians)
console.log(Math.acos(0.5)); // 1.0471975511965979 (60° in radians)
console.log(Math.atan(1)); // 0.7853981633974483 (45° in radians)
// Math.atan2() - angle from positive x-axis
console.log(Math.atan2(1, 1)); // 0.7853981633974483 (45°)
console.log(Math.atan2(-1, -1)); // -2.356194490192345 (-135°)
Hyperbolic Functions
// Hyperbolic functions
console.log(Math.sinh(0)); // 0
console.log(Math.cosh(0)); // 1
console.log(Math.tanh(0)); // 0
// Inverse hyperbolic functions
console.log(Math.asinh(1)); // 0.881373587019543
console.log(Math.acosh(2)); // 1.3169578969248166
console.log(Math.atanh(0.5)); // 0.5493061443340548
// Practical example: Catenary curve
function catenary(x, a = 1) {
return a * Math.cosh(x / a);
}
Min, Max, and Absolute Value
// Math.max() - returns largest value
console.log(Math.max(1, 2, 3)); // 3
console.log(Math.max(-1, -2, -3)); // -1
console.log(Math.max()); // -Infinity
// Math.min() - returns smallest value
console.log(Math.min(1, 2, 3)); // 1
console.log(Math.min(-1, -2, -3)); // -3
console.log(Math.min()); // Infinity
// With arrays
const numbers = [5, 2, 8, 1, 9];
console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 1
// Math.abs() - absolute value
console.log(Math.abs(-5)); // 5
console.log(Math.abs(5)); // 5
console.log(Math.abs(-0)); // 0
// Practical functions
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
console.log(clamp(10, 0, 5)); // 5
console.log(clamp(-5, 0, 100)); // 0
console.log(clamp(50, 0, 100)); // 50
function distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
function manhattan(x1, y1, x2, y2) {
return Math.abs(x2 - x1) + Math.abs(y2 - y1);
}
Random Number Generation
Basic Random Functions
// Math.random() - returns 0 to 1 (exclusive)
console.log(Math.random()); // e.g., 0.7394860476531409
// Random integer between min and max (inclusive)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 10)); // Random integer 1-10
console.log(randomInt(0, 100)); // Random integer 0-100
// Random float between min and max
function randomFloat(min, max) {
return Math.random() * (max - min) + min;
}
console.log(randomFloat(0, 1)); // Random float 0-1
console.log(randomFloat(1.5, 2.5)); // Random float 1.5-2.5
// Random boolean
function randomBoolean() {
return Math.random() < 0.5;
}
// Random from array
function randomElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
const colors = ['red', 'green', 'blue', 'yellow'];
console.log(randomElement(colors));
Advanced Random Functions
// Weighted random selection
function weightedRandom(items, weights) {
const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
let random = Math.random() * totalWeight;
for (let i = 0; i < items.length; i++) {
random -= weights[i];
if (random < 0) {
return items[i];
}
}
return items[items.length - 1];
}
const outcomes = ['common', 'rare', 'legendary'];
const weights = [70, 25, 5];
console.log(weightedRandom(outcomes, weights));
// Gaussian (normal) distribution
function gaussianRandom() {
let u = 0,
v = 0;
while (u === 0) u = Math.random();
while (v === 0) v = Math.random();
return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
}
// Shuffle array (Fisher-Yates)
function shuffle(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
// Random UUID generator
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
Sign and Integer Safety
// Math.sign() - returns sign of number
console.log(Math.sign(5)); // 1
console.log(Math.sign(-5)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(-0)); // -0
console.log(Math.sign(NaN)); // NaN
// Integer safety
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.isSafeInteger(9007199254740991)); // true
console.log(Number.isSafeInteger(9007199254740992)); // false
// Math.imul() - 32-bit integer multiplication
console.log(Math.imul(2, 4)); // 8
console.log(Math.imul(-1, 8)); // -8
console.log(Math.imul(0xffffffff, 2)); // -2
// Math.fround() - nearest 32-bit float
console.log(Math.fround(1.337)); // 1.3370000123977661
console.log(Math.fround(1.5)); // 1.5
Practical Applications
Geometry Calculations
class GeometryCalculator {
// Circle calculations
static circleArea(radius) {
return Math.PI * Math.pow(radius, 2);
}
static circleCircumference(radius) {
return 2 * Math.PI * radius;
}
// Triangle calculations
static triangleArea(base, height) {
return 0.5 * base * height;
}
static triangleAreaHeron(a, b, c) {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
// Rectangle calculations
static rectangleArea(width, height) {
return width * height;
}
static rectangleDiagonal(width, height) {
return Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
}
// 3D calculations
static sphereVolume(radius) {
return (4 / 3) * Math.PI * Math.pow(radius, 3);
}
static sphereSurfaceArea(radius) {
return 4 * Math.PI * Math.pow(radius, 2);
}
// Distance calculations
static distance2D(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
static distance3D(x1, y1, z1, x2, y2, z2) {
return Math.sqrt(
Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2)
);
}
}
Statistical Functions
class Statistics {
static mean(numbers) {
return numbers.reduce((sum, num) => sum + num, 0) / numbers.length;
}
static median(numbers) {
const sorted = [...numbers].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 0) {
return (sorted[mid - 1] + sorted[mid]) / 2;
}
return sorted[mid];
}
static mode(numbers) {
const frequency = {};
let maxFreq = 0;
let modes = [];
numbers.forEach((num) => {
frequency[num] = (frequency[num] || 0) + 1;
if (frequency[num] > maxFreq) {
maxFreq = frequency[num];
modes = [num];
} else if (frequency[num] === maxFreq) {
modes.push(num);
}
});
return modes;
}
static variance(numbers) {
const avg = this.mean(numbers);
const squaredDiffs = numbers.map((num) => Math.pow(num - avg, 2));
return this.mean(squaredDiffs);
}
static standardDeviation(numbers) {
return Math.sqrt(this.variance(numbers));
}
static percentile(numbers, p) {
const sorted = [...numbers].sort((a, b) => a - b);
const index = (p / 100) * (sorted.length - 1);
const lower = Math.floor(index);
const upper = Math.ceil(index);
const weight = index % 1;
if (lower === upper) {
return sorted[lower];
}
return sorted[lower] * (1 - weight) + sorted[upper] * weight;
}
}
Animation and Easing Functions
class Easing {
// Linear
static linear(t) {
return t;
}
// Quadratic
static easeInQuad(t) {
return t * t;
}
static easeOutQuad(t) {
return t * (2 - t);
}
static easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
// Cubic
static easeInCubic(t) {
return t * t * t;
}
static easeOutCubic(t) {
return --t * t * t + 1;
}
// Elastic
static easeInElastic(t) {
if (t === 0) return 0;
if (t === 1) return 1;
const p = 0.3;
return -Math.pow(2, 10 * (t - 1)) * Math.sin((t - 1.1) * 5 * Math.PI);
}
// Bounce
static easeOutBounce(t) {
if (t < 1 / 2.75) {
return 7.5625 * t * t;
} else if (t < 2 / 2.75) {
return 7.5625 * (t -= 1.5 / 2.75) * t + 0.75;
} else if (t < 2.5 / 2.75) {
return 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375;
} else {
return 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375;
}
}
}
// Animation example
function animate(duration, easing, callback) {
const start = performance.now();
function frame(currentTime) {
const elapsed = currentTime - start;
const progress = Math.min(elapsed / duration, 1);
const value = easing(progress);
callback(value);
if (progress < 1) {
requestAnimationFrame(frame);
}
}
requestAnimationFrame(frame);
}
Financial Calculations
class Financial {
// Compound interest
static compoundInterest(principal, rate, time, n = 1) {
return principal * Math.pow(1 + rate / n, n * time);
}
// Present value
static presentValue(futureValue, rate, periods) {
return futureValue / Math.pow(1 + rate, periods);
}
// Loan payment
static loanPayment(principal, rate, periods) {
const r = rate / 12; // Monthly rate
return (
(principal * r * Math.pow(1 + r, periods)) /
(Math.pow(1 + r, periods) - 1)
);
}
// ROI
static returnOnInvestment(gain, cost) {
return ((gain - cost) / cost) * 100;
}
// Currency rounding
static roundCurrency(amount) {
return Math.round(amount * 100) / 100;
}
}
Performance Optimization
// Cache frequently used values
const HALF_PI = Math.PI / 2;
const TWO_PI = Math.PI * 2;
const DEG_TO_RAD = Math.PI / 180;
const RAD_TO_DEG = 180 / Math.PI;
// Fast approximations
class FastMath {
// Fast inverse square root (Quake algorithm)
static fastInvSqrt(number) {
const threehalfs = 1.5;
let x2 = number * 0.5;
let y = number;
// Evil floating point bit level hacking
let i = new Float32Array(1);
i[0] = y;
let j = new Int32Array(i.buffer);
j[0] = 0x5f3759df - (j[0] >> 1);
let k = new Float32Array(j.buffer);
y = k[0];
y = y * (threehalfs - x2 * y * y);
return y;
}
// Fast sine approximation
static fastSin(x) {
x = x % TWO_PI;
if (x < -Math.PI) x += TWO_PI;
else if (x > Math.PI) x -= TWO_PI;
if (x < 0) {
return 1.27323954 * x + 0.405284735 * x * x;
} else {
return 1.27323954 * x - 0.405284735 * x * x;
}
}
}
// Lookup tables for expensive operations
class LookupTable {
constructor() {
this.sinTable = new Float32Array(360);
this.cosTable = new Float32Array(360);
for (let i = 0; i < 360; i++) {
const rad = i * DEG_TO_RAD;
this.sinTable[i] = Math.sin(rad);
this.cosTable[i] = Math.cos(rad);
}
}
sin(degrees) {
return this.sinTable[Math.floor(degrees) % 360];
}
cos(degrees) {
return this.cosTable[Math.floor(degrees) % 360];
}
}
Best Practices
-
Be aware of floating point precision
console.log(0.1 + 0.2); // 0.30000000000000004 // Use epsilon for comparisons function floatEquals(a, b, epsilon = Number.EPSILON) { return Math.abs(a - b) < epsilon; }
-
Validate inputs
function safeDivide(a, b) { if (b === 0) { throw new Error('Division by zero'); } return a / b; }
-
Use appropriate methods
// Use Math.hypot for distance calculations // Instead of: Math.sqrt(x*x + y*y) const distance = Math.hypot(x, y);
-
Consider performance
// Cache expensive calculations const PI_OVER_180 = Math.PI / 180; function toRadians(degrees) { return degrees * PI_OVER_180; }
Conclusion
The Math object provides essential mathematical functionality:
- Constants for common mathematical values
- Rounding methods for number formatting
- Power and root functions
- Trigonometric operations
- Random number generation
- Utility functions for calculations
Key takeaways:
- Understand floating-point precision limitations
- Use appropriate methods for specific tasks
- Consider performance for intensive calculations
- Validate inputs to prevent errors
- Cache frequently used values
- Use Math methods instead of manual calculations
Master the Math object to perform complex calculations and build mathematical applications!