The Math object provides constants and methods for mathematical operations. It is not a constructor — you never write new Math(). All methods and properties are static: call them directly as Math.methodName().

Common Properties

  Math.PI;    // 3.141592653589793
Math.E;     // 2.718281828459045 (Euler's number)
Math.LN2;   // 0.693... (natural log of 2)
Math.SQRT2; // 1.414... (square root of 2)
  

Rounding Methods

Method Behavior Example
Math.floor(x) Round down Math.floor(4.9)4
Math.ceil(x) Round up Math.ceil(4.1)5
Math.round(x) Round to nearest (half up) Math.round(4.5)5
Math.trunc(x) Remove fractional part Math.trunc(-4.9)-4
  // Banker's rounding note: Math.round(1.5) === 2, Math.round(2.5) === 3
// For consistent decimal rounding:
function roundTo(value, decimals) {
    const factor = Math.pow(10, decimals);
    return Math.round(value * factor) / factor;
}
roundTo(5.6789, 2); // 5.68
  

Min, Max, and Absolute Value

  Math.abs(-5);           // 5
Math.max(1, 5, 3);      // 5
Math.min(1, 5, 3);      // 1

// Spread arrays
let scores = [88, 92, 76, 95];
Math.max(...scores);    // 95
Math.min(...scores);    // 76
  

Empty array pitfall: Math.max(...[]) returns -Infinity. Guard against empty arrays in production code.

Power and Roots

  Math.pow(2, 10);     // 1024 (same as 2 ** 10)
Math.sqrt(16);     // 4
Math.cbrt(27);     // 3 (cube root)
Math.hypot(3, 4);  // 5 (Pythagorean theorem: √(3² + 4²))
  

Random Numbers

Math.random() returns a pseudo-random float in [0, 1):

  // Random integer from min to max (inclusive)
function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomInt(1, 10); // 1 through 10

// Random element from array
function randomItem(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}
randomItem(['rock', 'paper', 'scissors']);
  

Security note: Math.random() is not cryptographically secure. Use crypto.getRandomValues() for tokens, IDs, or anything security-sensitive.

  const array = new Uint32Array(1);
crypto.getRandomValues(array);
const secureRandom = array[0] / (0xFFFFFFFF + 1);
  

Trigonometry and Logarithms

  Math.sin(Math.PI / 2);  // 1
Math.cos(0);            // 1
Math.tan(Math.PI / 4);  // ~1

Math.log(Math.E);       // 1 (natural log)
Math.log10(100);        // 2
Math.log2(8);           // 3
  

Convert degrees to radians: radians = degrees * (Math.PI / 180).

Practical Examples

Calculate Hypotenuse

  function hypotenuse(a, b) {
    return Math.hypot(a, b);
}
hypotenuse(3, 4); // 5
  

Clamp a Value to a Range

  function clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
}
clamp(150, 0, 100); // 100
clamp(-5, 0, 100);  // 0
  

Format Currency (Display Only)

  function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount);
}
formatCurrency(1234.567); // "$1,234.57"
  

Use Intl.NumberFormat for display; use Math.round for internal calculations.

Generate a Random Color

  function randomHexColor() {
    return '#' + Math.floor(Math.random() * 0xFFFFFF)
        .toString(16)
        .padStart(6, '0');
}
  

Floating-Point Gotchas

JavaScript uses IEEE 754 floating-point, which causes precision issues:

  0.1 + 0.2;              // 0.30000000000000004
0.1 + 0.2 === 0.3;      // false

// Fix for comparisons:
function nearlyEqual(a, b, epsilon = 1e-10) {
    return Math.abs(a - b) < epsilon;
}
nearlyEqual(0.1 + 0.2, 0.3); // true
  

For financial calculations, consider integer cents or a library like decimal.js.

Best Practices

  • Use Math.trunc() instead of Math.floor() for negative numbers when you want toward zero.
  • Prefer ** operator over Math.pow() for readability: 2 ** 10.
  • Never use Math.random() for security-sensitive values.
  • Compare floats with an epsilon, not strict equality.
  • Use Intl APIs for locale-aware number formatting in user interfaces.

Troubleshooting

Issue Cause Fix
NaN result Invalid input like Math.sqrt(-1) Validate inputs before calling
Same “random” sequence Seeded PRNG in some environments Use crypto.getRandomValues()
Off-by-one in random range Wrong multiplier Use (max - min + 1) for inclusive max
-Infinity from Math.max() Empty array spread Check array length first

The Math object covers most numeric needs in everyday JavaScript. For matrices, statistics, or complex math, reach for specialized libraries — but know these core methods first.