JavaScript Tutorial · JavaScript Toolbox · Lesson 37 of 44

JavaScript Math

Rounding, powers, random numbers and other Math functions.

The Math object

Math holds constants and functions for common calculations:

Example 1Try it yourself
console.log(Math.PI);
console.log(Math.round(2.5), Math.round(-2.5));
console.log(Math.trunc(-4.7), Math.floor(-4.7));
console.log(Math.abs(-7), Math.sign(-7));
console.log(Math.sqrt(144), Math.cbrt(27), Math.pow(2, 10));
console.log(Math.max(3, 9, 1), Math.min(3, 9, 1));
console.log(Math.hypot(3, 4));

Output

3.141592653589793
3 -2
-4 -5
7 -1
12 3 1024
9 1
5

Random numbers

Math.random() returns a decimal from 0 (inclusive) to 1 (exclusive). Scale it to get a random integer in a range:

Example 2Try it yourself
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
const rolls = Array.from({ length: 10 }, () => randomInt(1, 6));
console.log(rolls);
console.log(rolls.every((r) => r >= 1 && r <= 6));

Output

[ 4, 1, 6, 6, 2, 3, 5, 1, 4, 2 ]
true

Math.random() is not secure. For tokens and passwords use crypto.getRandomValues() or crypto.randomUUID().

Test yourself

What range does Math.random() return?

  1. 0 to 1, both inclusive
  2. 0 (inclusive) to 1 (exclusive)
  3. 1 to 100
  4. -1 to 1
Show answer

Answer: 0 (inclusive) to 1 (exclusive)