Skip to content

JavaScript Math

The Math object is a built-in JavaScript object that provides various mathematical constants and functions. It's a static object where all properties and methods are accessed directly without creating an instance.

What is the Math Object

The Math object provides properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor and cannot be instantiated with new Math().

Characteristics

  1. Static Object: All properties and methods are static
  2. Not Instantiable: Cannot create instances of Math
  3. Built-in Object: Comes with JavaScript environment
  4. Cross-Platform: Behaves consistently across all JavaScript environments

Math Constants

javascript
// Basic mathematical constants
console.log(Math.E);       // 2.718281828459045 (Euler's number)
console.log(Math.PI);      // 3.141592653589793 (Pi)
console.log(Math.SQRT2);   // 1.4142135623730951 (Square root of 2)
console.log(Math.SQRT1_2); // 0.7071067811865476 (Square root of 1/2)
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)

// Usage examples
const circleArea = Math.PI * Math.pow(5, 2); // Circle area with radius 5
console.log(circleArea); // 78.53981633974483

const hypotenuse = Math.sqrt(Math.pow(3, 2) + Math.pow(4, 2));
console.log(hypotenuse); // 5

Basic Math Functions

Absolute Value and Sign

javascript
// Math.abs() - Absolute value
console.log(Math.abs(-5));    // 5
console.log(Math.abs(5));     // 5
console.log(Math.abs(-3.14)); // 3.14

// Math.sign() - Sign function (ES6)
console.log(Math.sign(5));   // 1 (positive)
console.log(Math.sign(-5));  // -1 (negative)
console.log(Math.sign(0));   // 0 (zero)
console.log(Math.sign(NaN)); // NaN

Rounding Functions

javascript
const num = 3.7;

// Math.floor() - Round down
console.log(Math.floor(num));   // 3
console.log(Math.floor(-3.7));  // -4

// Math.ceil() - Round up
console.log(Math.ceil(num));    // 4
console.log(Math.ceil(-3.7));   // -3

// Math.round() - Round to nearest integer
console.log(Math.round(num));   // 4
console.log(Math.round(3.4));   // 3
console.log(Math.round(3.5));   // 4
console.log(Math.round(-3.5));  // -3

// Math.trunc() - Truncate decimal part (ES6)
console.log(Math.trunc(num));   // 3
console.log(Math.trunc(-3.7));  // -3

Power and Root Functions

javascript
// Math.pow() - Power
console.log(Math.pow(2, 3));   // 8 (2^3)
console.log(Math.pow(4, 0.5)); // 2 (sqrt of 4)
console.log(Math.pow(10, 2));  // 100

// 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 (ES6)
console.log(Math.cbrt(27));  // 3
console.log(Math.cbrt(-8));  // -2

// Math.hypot() - Square root of sum of squares (ES6)
console.log(Math.hypot(3, 4));    // 5 (3² + 4² = 25, √25 = 5)
console.log(Math.hypot(1, 2, 3)); // 3.7416573867739413

Logarithm and Exponential Functions

javascript
// Math.exp() - e^x
console.log(Math.exp(1)); // 2.718281828459045 (e¹)
console.log(Math.exp(0)); // 1 (e⁰)

// Math.log() - Natural log (base e)
console.log(Math.log(Math.E)); // 1
console.log(Math.log(1));      // 0
console.log(Math.log(10));     // 2.302585092994046

// Math.log10() - Log base 10 (ES6)
console.log(Math.log10(10));   // 1
console.log(Math.log10(100));  // 2

// Math.log2() - Log base 2 (ES6)
console.log(Math.log2(2)); // 1
console.log(Math.log2(8)); // 3

Trigonometric Functions

javascript
// Helper functions for angle conversion
function toRadians(degrees) {
    return degrees * (Math.PI / 180);
}

function toDegrees(radians) {
    return radians * (180 / Math.PI);
}

// Math.sin() - Sine
console.log(Math.sin(0));            // 0
console.log(Math.sin(Math.PI / 2));  // 1
console.log(Math.sin(toRadians(30))); // ~0.5

// Math.cos() - Cosine
console.log(Math.cos(0));             // 1
console.log(Math.cos(Math.PI));       // -1
console.log(Math.cos(toRadians(60))); // ~0.5

// Math.tan() - Tangent
console.log(Math.tan(0));             // 0
console.log(Math.tan(toRadians(45))); // ~1

// Inverse trig functions
console.log(Math.asin(1)); // 1.5707963267948966 (π/2)
console.log(Math.acos(0)); // 1.5707963267948966 (π/2)
console.log(Math.atan(1)); // 0.7853981633974483 (π/4)
console.log(Math.atan2(1, 1)); // 0.7853981633974483 (π/4)

Min and Max Functions

javascript
// Math.max() - Maximum
console.log(Math.max(1, 2, 3, 4, 5));  // 5
console.log(Math.max(-1, -2, -3));     // -1
console.log(Math.max());                // -Infinity

// Math.min() - Minimum
console.log(Math.min(1, 2, 3, 4, 5));  // 1
console.log(Math.min(-1, -2, -3));     // -3
console.log(Math.min());                // Infinity

// With arrays
const numbers = [1, 5, 3, 9, 2];
console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 1

// Using apply (ES5 way)
console.log(Math.max.apply(null, numbers)); // 9

Random Number Function

javascript
// Math.random() - Random number between 0 and 1
console.log(Math.random()); // e.g., 0.8441828566137701

// Random integer in range
function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInt(1, 10));  // 1-10 random integer
console.log(randomInt(0, 100)); // 0-100 random integer

// Random float in range
function randomFloat(min, max, decimals = 2) {
    const factor = Math.pow(10, decimals);
    return Math.round((Math.random() * (max - min) + min) * factor) / factor;
}

console.log(randomFloat(1, 10)); // 1-10 random float

// Random boolean
function randomBoolean() {
    return Math.random() >= 0.5;
}

// Random array element
function randomElement(array) {
    return array[Math.floor(Math.random() * array.length)];
}

const fruits = ["apple", "banana", "orange", "grape"];
console.log(randomElement(fruits)); // Random fruit

Math Utility Class

javascript
class MathUtils {
    // Angle conversion
    static degreesToRadians(degrees) {
        return degrees * (Math.PI / 180);
    }
    
    static radiansToDegrees(radians) {
        return radians * (180 / Math.PI);
    }
    
    // Distance between two points
    static distance(x1, y1, x2, y2) {
        return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    }
    
    // Is prime number
    static isPrime(num) {
        if (num <= 1) return false;
        if (num <= 3) return true;
        if (num % 2 === 0 || num % 3 === 0) return false;
        
        for (let i = 5; i * i <= num; i += 6) {
            if (num % i === 0 || num % (i + 2) === 0) {
                return false;
            }
        }
        return true;
    }
    
    // Factorial
    static factorial(n) {
        if (n < 0) return NaN;
        if (n === 0 || n === 1) return 1;
        
        let result = 1;
        for (let i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }
    
    // Greatest common divisor
    static gcd(a, b) {
        a = Math.abs(a);
        b = Math.abs(b);
        while (b !== 0) {
            const temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    
    // Least common multiple
    static lcm(a, b) {
        return Math.abs(a * b) / this.gcd(a, b);
    }
    
    // Linear interpolation
    static lerp(start, end, t) {
        return start + (end - start) * t;
    }
    
    // Circle area
    static circleArea(radius) {
        return Math.PI * radius * radius;
    }
    
    // Sphere volume
    static sphereVolume(radius) {
        return (4 / 3) * Math.PI * Math.pow(radius, 3);
    }
    
    // Triangle area (Heron's formula)
    static triangleArea(a, b, c) {
        const s = (a + b + c) / 2;
        return Math.sqrt(s * (s - a) * (s - b) * (s - c));
    }
    
    // Clamp value to range
    static clamp(value, min, max) {
        return Math.min(Math.max(value, min), max);
    }
    
    // Map value from one range to another
    static map(value, inMin, inMax, outMin, outMax) {
        return ((value - inMin) / (inMax - inMin)) * (outMax - outMin) + outMin;
    }
    
    // Calculate percentage
    static percentage(value, total) {
        return (value / total) * 100;
    }
    
    // Discount price
    static discountPrice(originalPrice, discountPercent) {
        return originalPrice * (1 - discountPercent / 100);
    }
}

// Usage examples
console.log(MathUtils.degreesToRadians(180)); // 3.141592653589793
console.log(MathUtils.distance(0, 0, 3, 4));  // 5
console.log(MathUtils.isPrime(17));            // true
console.log(MathUtils.factorial(5));           // 120
console.log(MathUtils.gcd(12, 18));            // 6
console.log(MathUtils.lcm(12, 18));            // 36
console.log(MathUtils.lerp(0, 100, 0.5));      // 50
console.log(MathUtils.circleArea(5));          // 78.53981633974483
console.log(MathUtils.triangleArea(3, 4, 5));  // 6
console.log(MathUtils.clamp(15, 1, 10));       // 10
console.log(MathUtils.map(5, 0, 10, 0, 100));  // 50

Precision Math

javascript
class PrecisionMath {
    // Precise addition
    static add(a, b, precision = 10) {
        return parseFloat((a + b).toFixed(precision));
    }
    
    // Precise subtraction
    static subtract(a, b, precision = 10) {
        return parseFloat((a - b).toFixed(precision));
    }
    
    // Precise multiplication
    static multiply(a, b, precision = 10) {
        return parseFloat((a * b).toFixed(precision));
    }
    
    // Precise division
    static divide(a, b, precision = 10) {
        if (b === 0) throw new Error("Cannot divide by zero");
        return parseFloat((a / b).toFixed(precision));
    }
    
    // Compare with precision
    static isEqual(a, b, epsilon = Number.EPSILON) {
        return Math.abs(a - b) < epsilon;
    }
    
    // Round to decimals
    static round(value, decimals = 0) {
        const factor = Math.pow(10, decimals);
        return Math.round(value * factor) / factor;
    }
    
    // Floor to decimals
    static floor(value, decimals = 0) {
        const factor = Math.pow(10, decimals);
        return Math.floor(value * factor) / factor;
    }
    
    // Ceil to decimals
    static ceil(value, decimals = 0) {
        const factor = Math.pow(10, decimals);
        return Math.ceil(value * factor) / factor;
    }
}

// Usage
console.log(PrecisionMath.add(0.1, 0.2));       // 0.3
console.log(PrecisionMath.subtract(0.3, 0.1)); // 0.2
console.log(PrecisionMath.isEqual(0.1 + 0.2, 0.3)); // true
console.log(PrecisionMath.round(3.14159, 2));  // 3.14

Geometry Calculator

javascript
class GeometryCalculator {
    // Rectangle area
    static rectangleArea(width, height) {
        return width * height;
    }
    
    // Rectangle perimeter
    static rectanglePerimeter(width, height) {
        return 2 * (width + height);
    }
    
    // Circle area
    static circleArea(radius) {
        return Math.PI * radius * radius;
    }
    
    // Circle circumference
    static circleCircumference(radius) {
        return 2 * Math.PI * radius;
    }
    
    // Sector area
    static sectorArea(radius, angleInDegrees) {
        const angleInRadians = angleInDegrees * (Math.PI / 180);
        return 0.5 * radius * radius * angleInRadians;
    }
    
    // Sphere volume
    static sphereVolume(radius) {
        return (4 / 3) * Math.PI * Math.pow(radius, 3);
    }
    
    // Sphere surface area
    static sphereSurfaceArea(radius) {
        return 4 * Math.PI * radius * radius;
    }
    
    // Cylinder volume
    static cylinderVolume(radius, height) {
        return Math.PI * radius * radius * height;
    }
    
    // Point in rectangle
    static isPointInRectangle(px, py, x, y, width, height) {
        return px >= x && px <= x + width && py >= y && py <= y + height;
    }
    
    // Point in circle
    static isPointInCircle(px, py, cx, cy, radius) {
        return Math.sqrt(Math.pow(px - cx, 2) + Math.pow(py - cy, 2)) <= radius;
    }
}

// Usage
console.log(GeometryCalculator.circleArea(5)); // 78.53981633974483
console.log(GeometryCalculator.sphereVolume(5)); // 523.5987755982989
console.log(GeometryCalculator.isPointInCircle(2, 2, 0, 0, 5)); // true

Financial Calculator

javascript
class FinancialCalculator {
    // Compound interest
    static compoundInterest(principal, rate, time, frequency = 1) {
        return principal * Math.pow(1 + (rate / 100) / frequency, frequency * time);
    }
    
    // Simple interest
    static simpleInterest(principal, rate, time) {
        return principal * (rate / 100) * time;
    }
    
    // Loan monthly payment
    static loanPayment(principal, annualRate, months) {
        const monthlyRate = (annualRate / 100) / 12;
        if (monthlyRate === 0) return principal / months;
        return (principal * monthlyRate * Math.pow(1 + monthlyRate, months)) / 
               (Math.pow(1 + monthlyRate, months) - 1);
    }
    
    // Return on investment
    static roi(investment, returnAmount) {
        return ((returnAmount - investment) / investment) * 100;
    }
    
    // Present value
    static presentValue(futureValue, rate, periods) {
        return futureValue / Math.pow(1 + (rate / 100), periods);
    }
    
    // Future value
    static futureValue(presentValue, rate, periods) {
        return presentValue * Math.pow(1 + (rate / 100), periods);
    }
}

// Usage
console.log(FinancialCalculator.compoundInterest(10000, 5, 10)); // 16288.95
console.log(FinancialCalculator.loanPayment(100000, 5, 120));     // 1060.66
console.log(FinancialCalculator.roi(1000, 1500));                  // 50

Summary

Key points about JavaScript Math object:

  1. Basic Concept: Static object providing math constants and functions
  2. Constants: E, PI, SQRT2, etc.
  3. Basic Functions: abs(), sign(), floor(), ceil(), round(), trunc()
  4. Power and Roots: pow(), sqrt(), cbrt(), hypot()
  5. Exponential and Log: exp(), log(), log10(), log2()
  6. Trigonometric: sin(), cos(), tan() and inverse functions
  7. Hyperbolic: sinh(), cosh(), tanh() and inverse functions (ES6)
  8. Min/Max: max(), min()
  9. Random: random()
  10. Applications: Geometry calculations, financial calculations, precision math

The Math object is an essential tool for mathematical operations in JavaScript. In the next chapter, we will learn about JavaScript libraries.

Content is for learning and research only.