Chapter 23 of 31

JavaScript Math & Random Numbers

JavaScript provides a built-in Math object that contains useful properties and methods for performing mathematical operations.

You'll use it whenever you need to work with things like:

  • Rounding numbers

  • Finding the largest or smallest number

  • Calculating powers and square roots

  • Generating random numbers

  • Creating random values for games and applications

Let's see how it works.

The Math Object

The Math object is built into JavaScript, so we don't need to import anything.

For example:

console.log(Math.PI);

Output:

3.141592653589793

We can directly use methods from Math:

console.log(Math.sqrt(25));

Output:

5

Rounding Numbers

JavaScript provides several methods for rounding numbers.

Math.round()

Rounds a number to the nearest integer.

console.log(Math.round(4.4));
console.log(Math.round(4.6));

Output:

4
5

For example:

console.log(Math.round(10.5));

Output:

11

Math.floor()

Math.floor() always rounds down.

console.log(Math.floor(4.9));

Output:

4

Even:

console.log(Math.floor(4.1));

gives:

4

Math.ceil()

Math.ceil() always rounds up.

console.log(Math.ceil(4.1));

Output:

5

Even:

console.log(Math.ceil(4.9));

gives:

5

Math.trunc()

Math.trunc() simply removes the decimal part.

console.log(Math.trunc(4.9));
console.log(Math.trunc(4.1));

Output:

4
4

With negative numbers:

console.log(Math.trunc(-4.9));

Output:

-4

So the difference is:

Method

4.7

Purpose

Math.round()

5

Nearest integer

Math.floor()

4

Round down

Math.ceil()

5

Round up

Math.trunc()

4

Remove decimal part


Finding Minimum and Maximum

Math.max()

Returns the largest number.

console.log(Math.max(10, 50, 30, 20));

Output:

50

Math.min()

Returns the smallest number.

console.log(Math.min(10, 50, 30, 20));

Output:

10

We can also use them with an array by using the spread operator:

const numbers = [10, 50, 30, 20];

console.log(Math.max(...numbers));
console.log(Math.min(...numbers));

Output:

50
10

Absolute Value

Math.abs() returns the positive value of a number.

console.log(Math.abs(-10));

Output:

10

It can be useful when we only care about the distance between two values.

For example:

const difference = Math.abs(20 - 50);

console.log(difference);

Output:

30

Powers

We can calculate powers using Math.pow():

console.log(Math.pow(2, 3));

Output:

8

This means:

2³ = 8

However, modern JavaScript usually uses the exponentiation operator **:

console.log(2 ** 3);

Output:

8

Square Root

Math.sqrt() calculates the square root.

console.log(Math.sqrt(25));

Output:

5

Another example:

console.log(Math.sqrt(81));

Output:

9

Random Numbers

Now let's look at one of the most useful features of the Math object: generating random numbers.

We use:

Math.random()

It returns a pseudo-random decimal number between:

0 (inclusive) and 1 (exclusive)

For example:

console.log(Math.random());

You might get:

0.472819...

Run it again and you'll get another value.


Random Integer Between 0 and 9

Math.random() gives decimals, but we often need whole numbers.

We can combine it with Math.floor():

const number = Math.floor(Math.random() * 10);

console.log(number);

This generates:

0 to 9

Why?

Math.random()
      ↓
0.0 to less than 1.0

× 10
      ↓
0 to less than 10

Math.floor()
      ↓
0 to 9

Random Integer Between 1 and 10

To generate a number from 1 to 10:

const number = Math.floor(Math.random() * 10) + 1;

console.log(number);

Possible results:

1
2
3
...
10

The + 1 shifts the range from 0–9 to 1–10.


Random Integer in a Range

A very useful formula is:

Math.floor(Math.random() * (max - min + 1)) + min

For example, to generate a random number between 20 and 50:

const number = Math.floor(Math.random() * (50 - 20 + 1)) + 20;

console.log(number);

The result will always be between 20 and 50.

We can make this reusable with a function:

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

console.log(randomNumber(1, 100));

Now we can generate random integers in any range.


Generating a Random Array Element

Random numbers become especially useful when working with arrays.

Suppose we have:

const fruits = ["Apple", "Banana", "Mango", "Orange"];

We can select a random fruit:

const randomIndex = Math.floor(Math.random() * fruits.length);

console.log(fruits[randomIndex]);

Possible output:

Mango

or:

Apple

or any other element in the array.

This technique is commonly used in games, random quizzes, random recommendations, and many other applications.


A Practical Example: Dice Roll

Let's simulate a six-sided dice.

const dice = Math.floor(Math.random() * 6) + 1;

console.log(`You rolled: ${dice}`);

Possible output:

You rolled: 4

Every time you run the code, you'll get a value between 1 and 6.

We can turn it into a function:

function rollDice() {
    return Math.floor(Math.random() * 6) + 1;
}

console.log(rollDice());

Now we can call rollDice() whenever we need a new roll.


A Practical Example: Random Color

We can also generate random hexadecimal colors.

function randomColor() {
    const number = Math.floor(Math.random() * 16777216);

    return "#" + number.toString(16).padStart(6, "0");
}

console.log(randomColor());

Possible output:

#3fa82c

Here we're combining several concepts—random numbers, number conversion, and strings—to generate a random color.


Important Math Methods

Here are some of the methods you'll commonly use:

Method

Purpose

Math.round()

Round to nearest integer

Math.floor()

Round down

Math.ceil()

Round up

Math.trunc()

Remove decimal part

Math.abs()

Get absolute value

Math.max()

Find largest value

Math.min()

Find smallest value

Math.sqrt()

Calculate square root

Math.pow()

Calculate power

Math.random()

Generate pseudo-random number

Conclusion

The JavaScript Math object gives us many useful tools for mathematical operations.

The most important ones to remember are:

Math.round()
Math.floor()
Math.ceil()
Math.min()
Math.max()
Math.abs()
Math.sqrt()
Math.random()

And when working with random integers, remember this common pattern:

Math.floor(Math.random() * 10) + 1

This generates a random integer from 1 to 10.

Once you understand Math.random(), you'll be able to build simple things like dice games, random quizzes, number games, random selections, and many other interactive features.