-
-
Notifications
You must be signed in to change notification settings - Fork 2
JavaScript Math Guide
Mattscreative edited this page Feb 21, 2026
·
1 revision
- Introduction
- Math Object Properties
- Math Methods
- Working with Numbers
- BigInt for Large Numbers
- Practical Math Examples
- Working with Dates
- Practical Examples
JavaScript provides the built-in Math object for mathematical operations and constants. Unlike other objects, Math is not a constructor - all its properties and methods are static (you use Math.PI, not new Math()).
// Mathematical constants
console.log(Math.PI); // 3.141592653589793 (π)
console.log(Math.E); // 2.718281828459045 (e)
console.log(Math.LN2); // 0.6931471805599453 (ln(2))
console.log(Math.LN10); // 2.302585092994046 (ln(10))
console.log(Math.LOG2E); // 1.4426950408889634 (log₂e)
console.log(Math.LOG10E); // 0.4342944819032518 (log₁₀e)
console.log(Math.SQRT1_2); // 0.7071067811865476 (√½)
console.log(Math.SQRT2); // 1.4142135623730951 (√2)// Math.round() - round 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 toward positive)
// Math.floor() - round down (toward negative infinity)
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(-4.9)); // -5
// Math.ceil() - round up (toward positive infinity)
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(-4.1)); // -4
// Math.trunc() - remove fractional digits
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
// Comparing rounding methods
console.log("--- Comparing Rounding ---");
console.log("Value: 4.5, -4.5, 4.1, -4.1");
console.log("round:", Math.round(4.5), Math.round(-4.5), Math.round(4.1), Math.round(-4.1));
console.log("floor:", Math.floor(4.5), Math.floor(-4.5), Math.floor(4.1), Math.floor(-4.1));
console.log("ceil:", Math.ceil(4.5), Math.ceil(-4.5), Math.ceil(4.1), Math.ceil(-4.1));
console.log("trunc:", Math.trunc(4.5), Math.trunc(-4.5), Math.trunc(4.1), Math.trunc(-4.1));// Math.abs() - absolute value
console.log(Math.abs(-5)); // 5
console.log(Math.abs(5)); // 5
console.log(Math.abs(-0)); // 0
// Math.max() - maximum value
console.log(Math.max(1, 5, 3)); // 5
console.log(Math.max(-1, -5)); // -1
// Find max in array
const arr = [1, 5, 3, 9, 2];
console.log(Math.max(...arr)); // 9
// Math.min() - minimum value
console.log(Math.min(1, 5, 3)); // 1
console.log(Math.min(-1, -5)); // -5
// Find min in array
console.log(Math.min(...arr)); // 1
// Math.sum() - sum values (ES6+)
console.log(Math.sum(1, 2, 3, 4, 5)); // 15 (if using sum)// Math.pow() - exponentiation
console.log(Math.pow(2, 3)); // 8 (2³)
console.log(Math.pow(4, 0.5)); // 2 (√4)
console.log(Math.pow(2, -1)); // 0.5 (2⁻¹)
// Using ** operator (ES6+)
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.414213562...
console.log(Math.sqrt(-4)); // NaN
// Math.cbrt() - cube root
console.log(Math.cbrt(8)); // 2
console.log(Math.cbrt(-8)); // -2
// Math.hypot() - square root of sum of squares
console.log(Math.hypot(3, 4)); // 5 (3-4-5 triangle)
console.log(Math.hypot(1, 1, 1)); // √3 ≈ 1.732// All angles in radians - convert degrees to radians
const toRadians = degrees => degrees * Math.PI / 180;
const toDegrees = radians => radians * 180 / Math.PI;
console.log(toRadians(90)); // π/2 ≈ 1.571
console.log(toDegrees(Math.PI)); // 180
// Math.sin() - sine
console.log(Math.sin(Math.PI / 2)); // 1
console.log(Math.sin(0)); // 0
console.log(Math.sin(Math.PI)); // ~0
// Math.cos() - cosine
console.log(Math.cos(0)); // 1
console.log(Math.cos(Math.PI)); // -1
// Math.tan() - tangent
console.log(Math.tan(0)); // 0
console.log(Math.tan(Math.PI / 4)); // 1
// Inverse trigonometric functions
console.log(Math.asin(1)); // π/2
console.log(Math.acos(0)); // π/2
console.log(Math.atan(1)); // π/4
// Hyperbolic functions
console.log(Math.sinh(1)); // ~1.175
console.log(Math.cosh(1)); // ~1.543
console.log(Math.tanh(1)); // ~0.762// Math.sign() - sign of a 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
// Math.clamp() - clamp value between min and max (ES6+)
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
console.log(clamp(5, 0, 10)); // 5
console.log(clamp(-5, 0, 10)); // 0
console.log(clamp(15, 0, 10)); // 10
// Manual clamp using Math.min/Math.max
const clampAlt = (val, min, max) => Math.max(min, Math.min(max, val));// Math.log() - natural logarithm (ln)
console.log(Math.log(1)); // 0
console.log(Math.log(Math.E)); // 1
console.log(Math.log(10)); // ~2.303
// Math.log10() - base-10 logarithm
console.log(Math.log10(1)); // 0
console.log(Math.log10(10)); // 1
console.log(Math.log10(100)); // 2
// Math.log2() - base-2 logarithm
console.log(Math.log2(1)); // 0
console.log(Math.log2(2)); // 1
console.log(Math.log2(8)); // 3
// Math.exp() - e raised to power
console.log(Math.exp(1)); // ~2.718 (e)
console.log(Math.exp(0)); // 1
console.log(Math.exp(2)); // ~7.389 (e²)// Number properties
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324 (smallest positive)
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.NaN); // NaN
console.log(Number.POSITIVE_INFINITY); // Infinity
console.log(Number.NEGATIVE_INFINITY); // -Infinity
// Check for safe integers
console.log(Number.isSafeInteger(9007199254740991)); // true
console.log(Number.isSafeInteger(9007199254740992)); // false// Number.isFinite() - check if finite number
console.log(Number.isFinite(1)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(NaN)); // false
console.log(Number.isFinite("123")); // false (unlike global isFinite)
// Number.isNaN() - check if NaN
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(0/0)); // true
console.log(Number.isNaN(123)); // false
console.log(Number.isNaN("123")); // false (unlike global isNaN)
// Number.isInteger() - check if integer
console.log(Number.isInteger(5)); // true
console.log(Number.isInteger(5.5)); // false
console.log(Number.isInteger("5")); // false
// Number.isSafeInteger() - check if safe integer
console.log(Number.isSafeInteger(1e15)); // true
console.log(Number.isSafeInteger(1e16)); // false// Number() - convert to number
console.log(Number("123")); // 123
console.log(Number("12.5")); // 12.5
console.log(Number("12.34")); // 12.34
console.log(Number("123e5")); // 12300000
console.log(Number("hello")); // NaN
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
// parseInt() - parse integer from string
console.log(parseInt("123")); // 123
console.log(parseInt("123.45")); // 123
console.log(parseInt("123px")); // 123
console.log(parseInt("px123")); // NaN
console.log(parseInt("1010", 2)); // 10 (binary)
console.log(parseInt("FF", 16)); // 255 (hexadecimal)
// parseFloat() - parse float from string
console.log(parseFloat("123")); // 123
console.log(parseFloat("123.45")); // 123.45
console.log(parseFloat("123.45px")); // 123.45
// toFixed() - format with fixed decimal places
let num = 123.456789;
console.log(num.toFixed()); // "123"
console.log(num.toFixed(2)); // "123.46"
console.log(num.toFixed(4)); // "123.4568"
// toPrecision() - significant figures
console.log(num.toPrecision()); // "123.456789"
console.log(num.toPrecision(3)); // "123"
console.log(num.toPrecision(5)); // "123.46"
// toExponential() - exponential notation
console.log(num.toExponential()); // "1.23456789e+2"
console.log(num.toExponential(2)); // "1.23e+2"
// toString() - convert to string with base
console.log((255).toString()); // "255"
console.log((255).toString(2)); // "11111111"
console.log((255).toString(16)); // "ff"
console.log((10).toString(8)); // "12"// BigInt for integers beyond Number.MAX_SAFE_INTEGER
const bigNumber = 9007199254740993n;
console.log(bigNumber); // 9007199254740993n
console.log(typeof bigNumber); // "bigint"
// Operations with BigInt
const big1 = 123456789012345678901234567890n;
const big2 = 987654321098765432109876543210n;
console.log(big1 + big2); // 1111111110111111111011111111100n
console.log(big1 * big2); // 1219326311370217952261850327331...
console.log(big1 - big2); // -86419753208641975308641975320n
console.log(big1 / 1000000000n); // 123456789012n
// Cannot mix BigInt with Number
// console.log(big1 + 5); // TypeError
// Convert between Number and BigInt
console.log(Number(big1)); // 1.2345678901234568e+29 (precision loss!)
console.log(BigInt(123)); // 123n
// Check if BigInt
console.log(typeof 123n === "bigint"); // true// Calculate compound interest
function compoundInterest(principal, rate, timesCompounded, years) {
const rateDecimal = rate / 100;
return principal * Math.pow(1 + rateDecimal / timesCompounded, timesCompounded * years);
}
// $10,000 at 5% annual interest, compounded monthly for 10 years
const futureValue = compoundInterest(10000, 5, 12, 10);
console.log(`Future Value: $${futureValue.toFixed(2)}`);
// Calculate monthly payment for a loan
function calculateMonthlyPayment(principal, annualRate, years) {
const monthlyRate = annualRate / 100 / 12;
const numPayments = years * 12;
return principal * (monthlyRate * Math.pow(1 + monthlyRate, numPayments)) /
(Math.pow(1 + monthlyRate, numPayments) - 1);
}
const payment = calculateMonthlyPayment(250000, 6.5, 30);
console.log(`Monthly Payment: $${payment.toFixed(2)}`);
// Calculate loan amortization
function calculateAmortization(principal, annualRate, years) {
const monthlyRate = annualRate / 100 / 12;
const numPayments = years * 12;
const monthlyPayment = principal * (monthlyRate * Math.pow(1 + monthlyRate, numPayments)) /
(Math.pow(1 + monthlyRate, numPayments) - 1);
let balance = principal;
const schedule = [];
for (let month = 1; month <= numPayments; month++) {
const interestPayment = balance * monthlyRate;
const principalPayment = monthlyPayment - interestPayment;
balance -= principalPayment;
schedule.push({
month,
payment: monthlyPayment,
principal: principalPayment,
interest: interestPayment,
balance: Math.max(0, balance)
});
}
return schedule;
}
const schedule = calculateAmortization(10000, 5, 1);
console.log("First month:", schedule[0]);
// { month: 1, payment: 856.07, principal: 814.41, interest: 41.67, balance: 9185.59 }// Calculate mean (average)
function mean(arr) {
return arr.reduce((a, b) => a + b, 0) / arr.length;
}
console.log(mean([1, 2, 3, 4, 5])); // 3
// Calculate median
function median(arr) {
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 !== 0
? sorted[mid]
: (sorted[mid - 1] + sorted[mid]) / 2;
}
console.log(median([1, 2, 3, 4, 5])); // 3
console.log(median([1, 2, 3, 4])); // 2.5
// Calculate mode (most frequent)
function mode(arr) {
const frequency = {};
let maxFreq = 0;
let modes = [];
for (const value of arr) {
frequency[value] = (frequency[value] || 0) + 1;
if (frequency[value] > maxFreq) {
maxFreq = frequency[value];
modes = [value];
} else if (frequency[value] === maxFreq) {
modes.push(value);
}
}
return maxFreq === 1 ? [...new Set(arr)] : modes;
}
console.log(mode([1, 2, 2, 3, 3, 3])); // [3]
console.log(mode([1, 1, 2, 2, 3])); // [1, 2]
// Calculate standard deviation
function standardDeviation(arr) {
const avg = mean(arr);
const squareDiffs = arr.map(value => Math.pow(value - avg, 2));
return Math.sqrt(mean(squareDiffs));
}
console.log(standardDeviation([2, 4, 4, 4, 5, 5, 7, 9])); // 2
// Calculate variance
function variance(arr) {
const avg = mean(arr);
const squareDiffs = arr.map(value => Math.pow(value - avg, 2));
return mean(squareDiffs);
}// Calculate distance between two points
function distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
console.log(distance(0, 0, 3, 4)); // 5
// Calculate area of circle
function circleArea(radius) {
return Math.PI * Math.pow(radius, 2);
}
console.log(circleArea(5)); // 78.5398...
// Calculate area of triangle using Heron's formula
function triangleArea(a, b, c) {
const s = (a + b + c) / 2; // semi-perimeter
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
console.log(triangleArea(3, 4, 5)); // 6
// Calculate volume of sphere
function sphereVolume(radius) {
return (4/3) * Math.PI * Math.pow(radius, 3);
}
console.log(sphereVolume(5)); // 523.598...
// Calculate volume of cylinder
function cylinderVolume(radius, height) {
return Math.PI * Math.pow(radius, 2) * height;
}
console.log(cylinderVolume(3, 10)); // 282.743...
// Calculate surface area of sphere
function sphereSurfaceArea(radius) {
return 4 * Math.PI * Math.pow(radius, 2);
}
console.log(sphereSurfaceArea(5)); // 314.159...// 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
// 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
// Random element from array
function randomElement(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
console.log(randomElement(['red', 'green', 'blue'])); // Random color
// Shuffle array (Fisher-Yates)
function shuffleArray(arr) {
const shuffled = [...arr];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [sh shuffled[i]];
}
return shuffleduffled[j],;
}
console.log(shuffleArray([1, 2, 3, 4, 5]));
// Random boolean with probability
function randomBoolean(probability = 0.5) {
return Math.random() < probability;
}
console.log(randomBoolean(0.3)); // 30% chance of true// Create date
const now = new Date();
console.log(now); // Current date/time
// Create specific date
const date1 = new Date(2024, 0, 15); // January 15, 2024
const date2 = new Date("2024-01-15");
const date3 = new Date(2024, 0, 15, 14, 30, 0); // With time
// Get date components
console.log(now.getFullYear()); // 2024
console.log(now.getMonth()); // 0-11 (January = 0)
console.log(now.getDate()); // 1-31
console.log(now.getDay()); // 0-6 (Sunday = 0)
console.log(now.getHours()); // 0-23
console.log(now.getMinutes()); // 0-59
console.log(now.getSeconds()); // 0-59
console.log(now.getMilliseconds()); // 0-999
console.log(now.getTime()); // Unix timestamp (ms since 1970)
// Format date
function formatDate(date) {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return `${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
}
console.log(formatDate(new Date())); // "Feb 21, 2024"
// Calculate days between dates
function daysBetween(date1, date2) {
const oneDay = 24 * 60 * 60 * 1000;
return Math.round(Math.abs(date1 - date2) / oneDay);
}
const d1 = new Date(2024, 0, 1);
const d2 = new Date(2024, 0, 15);
console.log(daysBetween(d1, d2)); // 14// Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
// Fahrenheit to Celsius
function fahrenheitToCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
// Celsius to Kelvin
function celsiusToKelvin(celsius) {
return celsius + 273.15;
}
console.log(celsiusToFahrenheit(0)); // 32
console.log(celsiusToFahrenheit(100)); // 212
console.log(fahrenheitToCelsius(32)); // 0
console.log(celsiusToKelvin(0)); // 273.15// Calculate percentage
function percentage(value, total) {
return (value / total) * 100;
}
console.log(percentage(25, 100)); // 25
// Calculate percentage change
function percentageChange(oldValue, newValue) {
return ((newValue - oldValue) / oldValue) * 100;
}
console.log(percentageChange(100, 125)); // 25
// Calculate discount price
function discountPrice(originalPrice, discountPercent) {
return originalPrice * (1 - discountPercent / 100);
}
console.log(discountPrice(100, 20)); // 80
// Calculate tax
function addTax(amount, taxRate) {
return amount * (1 + taxRate / 100);
}
console.log(addTax(100, 8.5)); // 108.5// Factorial
function factorial(n) {
if (n < 0) return NaN;
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
console.log(factorial(0)); // 1
// Fibonacci
function fibonacci(n) {
if (n <= 1) return n;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
[a, b] = [b, a + b];
}
return b;
}
console.log(fibonacci(10)); // 55
// Check prime
function isPrime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 === 0 || n % 3 === 0) return false;
for (let i = 5; i * i <= n; i += 6) {
if (n % i === 0 || n % (i + 2) === 0) return false;
}
return true;
}
console.log(isPrime(17)); // true
console.log(isPrime(18)); // false
// Greatest Common Divisor (GCD)
function gcd(a, b) {
a = Math.abs(Math.floor(a));
b = Math.abs(Math.floor(b));
while (b) {
[a, b] = [b, a % b];
}
return a;
}
console.log(gcd(48, 18)); // 6
// Least Common Multiple (LCM)
function lcm(a, b) {
return Math.abs(a * b) / gcd(a, b);
}
console.log(lcm(4, 6)); // 12// Rounding
Math.round(x); // Nearest integer
Math.floor(x); // Round down
Math.ceil(x); // Round up
Math.trunc(x); // Remove decimals
// Basic
Math.abs(x); // Absolute value
Math.max(a, b); // Maximum
Math.min(a, b); // Minimum
// Power & Root
Math.pow(x, y); // x^y
Math.sqrt(x); // Square root
Math.cbrt(x); // Cube root
// Trigonometry (radians)
Math.sin(x);
Math.cos(x);
Math.tan(x);
// Logs & Exp
Math.log(x); // Natural log
Math.log10(x); // Base-10 log
Math.log2(x); // Base-2 log
Math.exp(x); // e^x
// Other
Math.sign(x); // -1, 0, or 1
Math.hypot(a, b); // √(a² + b²)
Math.random(); // 0 to 1