Math Object

Math is a built-in object with static methods for mathematical operations. Unlike Date, it is not a constructor — you use its methods directly with Math.methodName().

Common Math Methods

  • Math.abs(x) — Returns the absolute value of x.
  • Math.sign(x) — Returns the sign of x (-1, 0, or 1).
  • Math.min(...) — Returns the smallest of its arguments.
  • Math.max(...) — Returns the largest of its arguments.
  • Math.pow(x, y) — Returns x to the power y.
  • Math.sqrt(x) — Returns the positive square root of x.
console.log(Math.abs(-5));  // 5
console.log(Math.sign(-10));  // -1
console.log(Math.min(3, 1, 4, 1, 5));  // 1
console.log(Math.max(3, 1, 4, 1, 5));  // 5
console.log(Math.pow(2, 3));  // 8
console.log(Math.sqrt(16));  // 4

Rounding Functions

  • Math.round(x) — Returns the nearest integer.
  • Math.floor(x) — Returns the largest integer less than or equal to x.
  • Math.ceil(x) — Returns the smallest integer greater than or equal to x.
  • Math.trunc(x) — Returns the integer portion, removing any fractional digits.
console.log(Math.round(4.5));  // 5
console.log(Math.round(4.4));  // 4
console.log(Math.floor(5.9));  // 5
console.log(Math.ceil(5.1));  // 6
console.log(Math.trunc(5.9));  // 5

Rounding with Negative Numbers

Negative arguments are easy to get wrong. Look at which way each one rounds:

console.log(Math.ceil(7.004));  // 8
console.log(Math.ceil(-7.004));  // -7  (not -8!)
console.log(Math.floor(5.05));  // 5
console.log(Math.floor(-5.05));  // -6  (not -5!)

ceil(-7.004) returns -7 because -7 is greater than -7.004. Similarly, floor(-5.05) returns -6 because -6 is less than -5.05.

Random Numbers

Math.random() returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).

console.log(Math.random());  // 0 to < 1

// Random integer from 0 to 9
console.log(Math.floor(Math.random() * 10));

// Random integer from 1 to 10
console.log(Math.floor(Math.random() * 10) + 1);

Logarithmic Functions

  • Math.log(x) — Returns the natural logarithm (base e) of x.
  • Math.log2(x) — Returns the base-2 logarithm of x.
  • Math.log10(x) — Returns the base-10 logarithm of x.
  • Math.exp(x) — Returns .
console.log(Math.log(Math.E));  // 1
console.log(Math.log2(8));  // 3
console.log(Math.log10(1000));  // 3
console.log(Math.exp(1));  // 2.718281828459045

Math Constants

Math provides commonly used mathematical constants:

  • Math.E — Euler’s number (~2.718)
  • Math.PI — Pi (~3.14159)
  • Math.SQRT2 — Square root of 2
console.log(Math.E);  // 2.718281828459045
console.log(Math.PI);  // 3.141592653589793
console.log(Math.SQRT2);  // 1.4142135623730951