SyntaxStudy
Sign Up
JavaScript Beginner 6 min read

The Math Object

The JavaScript Math Object

The built-in Math object is a namespace containing mathematical constants and functions. Unlike most JavaScript objects, you never instantiate it — all properties and methods are accessed directly on Math. It provides everything from basic rounding to trigonometry and logarithms.

Rounding Methods

Math.round(x) rounds to the nearest integer (0.5 rounds up). Math.floor(x) always rounds down toward negative infinity. Math.ceil(x) always rounds up toward positive infinity. Math.trunc(x) removes the decimal part without rounding.

Math.random()

Math.random() returns a pseudo-random float in the range [0, 1). To generate a random integer between min and max (inclusive), use the formula Math.floor(Math.random() * (max - min + 1)) + min.

Other Useful Methods

  • Math.abs(x) — absolute value
  • Math.max(...values) and Math.min(...values) — largest/smallest
  • Math.pow(base, exp) — exponentiation (prefer the ** operator)
  • Math.sqrt(x) — square root
Example
console.log(Math.round(4.5));  // 5
console.log(Math.round(4.4));  // 4
console.log(Math.floor(4.9));  // 4
console.log(Math.ceil(4.1));   // 5
console.log(Math.trunc(-4.9)); // -4
console.log(Math.abs(-7));     // 7
console.log(Math.max(1, 5, 3, 9, 2)); // 9
console.log(Math.min(1, 5, 3, 9, 2)); // 1
console.log(Math.sqrt(16));    // 4
console.log(Math.PI);          // 3.141592653589793
const rand = Math.floor(Math.random() * 6) + 1;
console.log(rand); // random 1-6
Pro Tip

Use Math.floor(Math.random() * n) to get a random integer from 0 to n-1. Add a minimum value to shift the range — this is the standard dice-roll pattern in JavaScript.