Free beginner tutorial

JavaScript Math Object and Random Numbers

The built-in JavaScript Math object provides constants and methods for common calculations. Learn rounding, minimum and maximum values, and how to generate a random integer for simple activities such as a dice roll.

Quick answer: use methods such as Math.round(), Math.floor(), Math.ceil() and Math.max(). For an integer from 1 to 6, use Math.floor(Math.random() * 6) + 1.

Use the Math object

Math is a built-in object, so you call its methods directly. You do not create it with new. The Math.PI constant is useful for circle calculations.

const radius = 5;
const area = Math.PI * radius ** 2;
console.log(area); // about 78.54

Round numbers in different ways

Math.round() rounds to the nearest integer, Math.floor() rounds down, Math.ceil() rounds up, and Math.trunc() removes the decimal part toward zero. For negative numbers, floor and truncation differ: Math.floor(-4.2) is -5, while Math.trunc(-4.2) is -4.

console.log(Math.round(4.6)); // 5
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1));  // 5
console.log(Math.trunc(4.9)); // 4

Find the smallest or largest value

Use Math.min() and Math.max() to compare numbers. With an array, spread its values into the method.

const scores = [72, 91, 84];
console.log(Math.min(...scores)); // 72
console.log(Math.max(...scores)); // 91

Generate a random integer in a range

Math.random() returns a pseudo-random decimal greater than or equal to 0 and less than 1. Scale it, round it down, then add the minimum to include both endpoints of an integer range.

function randomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInteger(1, 6)); // an integer from 1 through 6

This is suitable for simple games and demonstrations. Math.random() is not designed for passwords, security tokens or other security-sensitive values; use the Web Crypto API for those.

When should you use JavaScript Math?

Use Math for everyday numeric calculations such as rounding a price for display, comparing scores, finding a circle area or choosing a random game outcome. Keep the original precise value when rounding is only for display.

Continue learning

Review operators and expressions for arithmetic, and arrays for working with lists of values.

For another beginner reference, see the W3Schools JavaScript Math tutorial. For the behavior of random values and security guidance, see MDN's Math.random() reference.